I have below string
ids = ["4,5,6"]
when I do
ids = ["4,5,6"].split(',')
Then I get ids as [["4,5,6"]]
can I do something to get ids as [4, 5, 6] ?
There are many ways to do it. More generic version (if you expect more than one string in the original array e.g.: ["4,5,6", "1,2,3"]):
> ["4,5,6"].flat_map{ |i| i.split(',') }.map(&:to_i)
=> [4, 5, 6]
> ["4,5,6", "1,2,3"].flat_map{ |i| i.split(',') }.map(&:to_i)
=> [4, 5, 6, 1, 2, 3]
My answer appears to be less concise than the accepted one and I'm fairly new to Ruby. I think that you can use ! to alter the Array in place.
ids=["4,5,6"];
new_ids=[];
new_ids.flatten.each do |i| new_ids.push(i.to_i) end;
new_ids
[4, 5, 6]
.each, and you will see a lot of ruby code, you will not understand, if you do not now .map .inject .reduct and stuff like .map(&:to_i)
idscome from in the first place? I would understandids = ["4" ,"5", "6"]orids = "4,5,6"but that string within an array smells like a bug elsewhere.