Hash#inject argument syntax

B

Brian Buckley

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)
 
E

Eero Saynatkari

Brian said:
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)
 
R

Robert Klemme

Brian said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top