简体   繁体   中英

How to map arrays using with_index in ruby ?

I've the following code for mapping the nD array. If the input are [[C, "O"], [C, "O"], [C, "#"], [C]] the output is "COCOC#C" . I want the output to be C(O)COC#C this is the when there are two elements in first array the 2nd element should be in brackets. I've used the following code, I just couldn't implement the use of with_index function.

def format2smi
  # return a Smiles compliant chemical name as a string

  map do |element|
    format_step(element)
  end.join('')    #.join(')')

end # format2smi

protected

def format_step(e)
  e.map.with_index do |x,i|

    if x.is_a?(Array)

x="("+x[1]+")"

"(#{ format_step(x) })" # calling the same function
    else  
      x.to_s # convert to string and return
    end
  end.join('')   #gsub("", "(").gsub("", ")") # map returns an array of strings, join
end

If you need the brackets only on the first element, it's enough to just do:

array = [['C', 'O'], ['C', 'O'], ['C', '#'], ['C']]

array.first[1] = "(#{array.first[1]})" if array.first.size == 2
array.join # => "C(O)COC#C"

I've resolved the issue. So stupid of me. :/

 def format_step(e)
  e.map.with_index do |x,i|

    if x.is_a?(Array)
      "(#{ format_step(x) })" # calling the same function
    else  
      if i ==0
        x.to_s
      else
       "("+x.to_s+")"
      end
      # convert to string and return
    end
  end.join('')
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM