3

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.

3
  • [["2000", "2004"], ["2005", "2007"]].map{|row| row.map(&:to_i)} works... Commented Apr 10, 2018 at 4:55
  • 1
    @dawg, you may have missed that halfelf gave that as a solution earlier. Commented Apr 10, 2018 at 6:36
  • 3
    a.each do |a| – re-using an outer variable name (variable shadowing) can lead to confusion. Don't do that. Commented Apr 10, 2018 at 7:45

4 Answers 4

8

How about "two dimensional" map?

a = [["2000", "2004"], ["2005", "2007"]]
a.map {|i| i.map(&:to_i) }  # => [[2000, 2004], [2005, 2007]]
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

4

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.)

4 Comments

why would that use less memory? can you expand on that @mudasobwa?
@pascalbetz After a careful re-think, I am to admit I was wrong. Updated the answer.
thanks for updating. Actually I was not "pointing out", just wondering why it could use less memory. Still wondering.... might write a benchmark at some point.
@pascalbetz it's even slightly less efficient because – unlike map – the array has to be resized as new elements are being added.
1

Out of curiosity:

a = [["2000", "2004"], ["2005", "2007"]]
a.flatten.map(&:to_i).each_slice(2).to_a
#⇒ [[2000, 2004], [2005, 2007]]

2 Comments

It's curious that this was awarded the greenie considering that it only works when a.size == a[0].size == a[1].size == 2.
Indeed, I was also surprised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.