Reputation: 1409
I have a nested array with string values:
a = [["2000", "2004"], ["2005", "2007"]]
I am converting the value to integer like this:
int_val = []
a.each do |a|
int_val << a.map(&:to_i)
end
int_val #=> [[2000, 2004], [2005, 2007]]
Is there any short solution or one line code for this? [["2000", "2004"], ["2005", "2007"]].map(&:to_i)
will not work.
Upvotes: 3
Views: 171
Reputation: 121020
Out of curiosity:
a = [["2000", "2004"], ["2005", "2007"]]
a.flatten.map(&:to_i).each_slice(2).to_a
#⇒ [[2000, 2004], [2005, 2007]]
Upvotes: 1
Reputation: 121020
Use Enumerable#each_with_object
:
a = [["2000", "2004"], ["2005", "2007"]]
a.each_with_object([]) do |a, int_val|
int_val << a.map(&:to_i)
end
#⇒ [[2000, 2004], [2005, 2007]]
It should be less memory-consuming than (credits @pascalbetz for pointing out that’s not true.)map.map
.
Upvotes: 4
Reputation: 9508
A single map
.
a.map { |i, j| [i.to_i, j.to_i] }
Of course this is not a general solution, but is good for your example.
Upvotes: 4
Reputation: 10107
How about "two dimensional" map
?
a = [["2000", "2004"], ["2005", "2007"]]
a.map {|i| i.map(&:to_i) } # => [[2000, 2004], [2005, 2007]]
Upvotes: 8