Reputation: 301
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]
?
Upvotes: 1
Views: 773
Reputation: 13
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]
Upvotes: 1
Reputation: 13477
You're trying to split an array, try to split a string instead:
["4,5,6"].first.split(',')
#=> ["4", "5", "6"]
After that you can simply convert it to an array of ints:
["4", "5", "6"].map(&:to_i)
#=> [4, 5, 6]
Upvotes: 1
Reputation: 6628
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]
Upvotes: 1