Hash#inject argument syntax

The code below works but I do not understand the "(key, value)"
parenthesis syntax. I have not seen it before. Could someone
explain?

--Brian

(from Rails' active_support)
class Hash
def symbolize_keys
   inject({}) do |options, (key, value)|
    options[key.to_sym] = value
    options
  end
end
(above code from Rails' active_support)

Brian Buckley wrote:

The code below works but I do not understand the "(key, value)"
parenthesis syntax. I have not seen it before. Could someone
explain?

--Brian

(from Rails' active_support)
class Hash
def symbolize_keys
   inject({}) do |options, (key, value)|

Hash#each, as you may know, actually produces an Array
of Arrays (key-value pairs). Here what is being passed
is actually one of those pairs--the parenthesised syntax
uses Ruby's assignment rules and splats the Array to
two distinct variables. Consider it the same as:

key, value = ['key', 'value']

···

    options[key.to_sym] = value
    options
  end
end
end
(above code from Rails' active_support)

--
Posted via http://www.ruby-forum.com/.

Brian Buckley wrote:

The code below works but I do not understand the "(key, value)"
parenthesis syntax. I have not seen it before. Could someone
explain?

--Brian

(from Rails' active_support)
class Hash
def symbolize_keys
   inject({}) do |options, (key, value)|

Hash#each, as you may know, actually produces an Array
of Arrays (key-value pairs). Here what is being passed
is actually one of those pairs--the parenthesised syntax
uses Ruby's assignment rules and splats the Array to
two distinct variables. Consider it the same as:

key, value = ['key', 'value']

The mechanism at work here is a more general pattern matching which also is done for regular assignments:

>> (a,(b,c),d,(e,(f,g))) = 1,[2,3],4,[5,[6,7]]
=> [1, [2, 3], 4, [5, [6, 7]]]
>> a
=> 1
>> b
=> 2
>> c
=> 3
>> d
=> 4
>> e
=> 5
>> f
=> 6
>> g
=> 7

Works also with the star operator:

>> (a,(b,c),d,(e,(f,*g))) = 1,[2,3],4,[5,[6,7,8]]
=> [1, [2, 3], 4, [5, [6, 7, 8]]]
>> g
=> [7, 8]

Kind regards

  robert

···

On 30.08.2006 02:23, Eero Saynatkari wrote: