From: Robert Klemme Date: 2007-01-14T19:45:05+09:00 Subject: Re: How does Array.map work for 2D arrays? On 14.01.2007 11:21, Karthik Nar wrote: > I was reading this example: > > pt = [ [ "Check", "check" ], [ "Credit card", "cc" ], [ "Purchase > order", "po" ] ] > pt.map {|value| value} > > Displays the 2D Array elements as expected => [["Check", "check"], > ["Credit card", "cc"], ["Purchase order", "po"]] > > but a two-parameter block suppled to map like below: > >>> pt.map {|disp, value| value} > => ["check", "cc", "po"] > > is able to give me the second element of the 2D array. > > i looked in the ruby doc and on the net for examples, but 2D arrays are > typically not covered. > > while, i love this functionality, my question is - > > How does this 2 parameter variant really work? > > How does the array.map "figure out" and pass disp to param1 and value to > param2? It doesn't really have to do anything at all: irb(main):001:0> def foo() yield 1,2 end => nil irb(main):002:0> foo {|a| p a} (irb):2: warning: multiple values for a block parameter (2 for 1) from (irb):1 [1, 2] => nil irb(main):003:0> foo {|*a| p a} [1, 2] => nil irb(main):004:0> foo {|a,b| p a} 1 => nil irb(main):005:0> def foo() yield [1,2] end => nil irb(main):006:0> foo {|a| p a} [1, 2] => nil irb(main):007:0> foo {|*a| p a} [[1, 2]] => nil irb(main):008:0> foo {|a,b| p a} 1 => nil You see in line 6 and 8 how it works. However, map could also evaluate the block's arity: irb(main):009:0> def foo(&b) p b.arity; b[1,2] end => nil irb(main):010:0> foo {|a| p a} 1 (irb):10: warning: multiple values for a block parameter (2 for 1) from (irb):9 [1, 2] => nil irb(main):011:0> foo {|a,b| p a} 2 1 => nil irb(main):012:0> foo {|*a| p a} -1 [1, 2] => nil irb(main):013:0> def foo(&b) p b.arity; b[[1,2]] end => nil irb(main):014:0> foo {|a| p a} 1 [1, 2] => nil irb(main):015:0> foo {|a,b| p a} 2 1 => nil irb(main):016:0> foo {|*a| p a} -1 [[1, 2]] => nil HTH robert