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!

SethS
  • 449
  • 4
  • 12

3 Answers3

3

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

a.map { |ar| ar.map { |e| e + 1 } }
sunnyrjuneja
  • 6,033
  • 2
  • 32
  • 51
  • 3
    `a.map { |ar| ar.map(&:next) }` to avoid opening two blocks :) – Anthony Alberto Nov 09 '12 at 03:02
  • 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|`? – sunnyrjuneja Nov 09 '12 at 03:04
  • 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 – Anthony Alberto Nov 09 '12 at 03:07
  • Is it not possible to do something like `a.map(&:map)` and somehow pass `&next` to that? – sunnyrjuneja Nov 09 '12 at 03:09
  • But I added an answer to declare a method that allows us to use only one `map` when we do the call, the other being hidden in the method of course – Anthony Alberto Nov 09 '12 at 03:12
  • Thanks Anthony. What is the `&:` form called? It looks like a block but I don't know what its called when you pass it like that. – sunnyrjuneja Nov 09 '12 at 03:15
  • 1
    I didn't know how it's called until I read a comment here : http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby. Apparently code `pretzel colon` ... also there's a full explanation of how the magick works in it, a good read – Anthony Alberto Nov 09 '12 at 03:24
  • @Sunny. Why `+=` instead of `+`? – tokland Nov 09 '12 at 08:25
3

Just for fun :

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

#Tada!
a.map(&:increment)
Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
0
a.map { |xs| xs.map(&:succ) }
#=> [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
tokland
  • 66,169
  • 13
  • 144
  • 170