[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Hash#inject argument syntax

Brian Buckley

8/29/2006 11:29:00 PM

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
end
(above code from Rails' active_support)

2 Answers

e

8/30/2006 12:23:00 AM

0

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

Robert Klemme

8/30/2006 8:54:00 AM

0

On 30.08.2006 02:23, Eero Saynatkari wrote:
> 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