0

I have a multidimensional array in ruby like this one:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

How do I add "1" to each element. For instance, I want to end up with something like this:

a = [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

Thanks in advance!

3 Answers 3

3

There might be a slightly more clever one liner but this is fairly clear.

a.map { |ar| ar.map { |e| e + 1 } }
Sign up to request clarification or add additional context in comments.

8 Comments

a.map { |ar| ar.map(&:next) } to avoid opening two blocks :)
Thanks, I had been sitting in irb for a few minutes trying to figure it out. Is it possible to do it without declaring |ar|?
That's what I was thinking about, but we'd need to declare a method on Array that takes each elements and adds 1 to them since there's nothing like that in the standard library
Is it not possible to do something like a.map(&:map) and somehow pass &next to that?
I didn't know how it's called until I read a comment here : stackoverflow.com/questions/1217088/…. Apparently code pretzel colon ... also there's a full explanation of how the magick works in it, a good read
|
3

Just for fun :

class Array
  def increment
    map(&:next)
  end
end

#Tada!
a.map(&:increment)

Comments

0
a.map { |xs| xs.map(&:succ) }
#=> [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

Comments

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.