oj5th
oj5th

Reputation: 1409

Parse string values into integer in a nested array

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

Answers (4)

Aleksei Matiushkin
Aleksei Matiushkin

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

Aleksei Matiushkin
Aleksei Matiushkin

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 map.map. (credits @pascalbetz for pointing out that’s not true.)

Upvotes: 4

Sagar Pandya
Sagar Pandya

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

halfelf
halfelf

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

Related Questions