Bloc param parens |memo, (a, b)|

T

Tj Holowaychuk

In Ruby < 1.9 what does this really do? For example I wrote

class String
def tokenize! hash
hash.inject(self) { |s, (k, v)| s.gsub! /:#{k}/, v }
end
end

Which has a usage of:
'Welcome :name, enjoy your :eek:bject'.tokenize!({ :name => 'TJ', :eek:bject
=> 'cookie' })

anyways, the inject did not work as desired until I put parens around
the last two parameters, yet I do not entirely understand whats going
here! does this just cause the distribution of the variables to change?
 
G

Gary Wright

In Ruby < 1.9 what does this really do? For example I wrote

class String
def tokenize! hash
hash.inject(self) { |s, (k, v)| s.gsub! /:#{k}/, v }
end
end

Which has a usage of:
'Welcome :name, enjoy your :eek:bject'.tokenize!({ :name => 'TJ', :eek:bject
=> 'cookie' })

anyways, the inject did not work as desired until I put parens around
the last two parameters, yet I do not entirely understand whats going
here! does this just cause the distribution of the variables to
change?

When you enumerate over a hash you get a series of arrays. Each array
has two elements: [key, value]. If your inject block only has two
arguments
defined, the second argument will be an array of two elements. When you
insert the parens the second argument is decomposed according to Ruby's
multiple assignment rules. Like this:

k,v = array[0], array[1]

Gary Wright
 
T

Tj Holowaychuk

Thanks for the reply! I get it now, just never really took the time to
check that stuff out

def test &block
yield 1, [2, 3]
end

test do |a, b, c|
p a
p b
p c
end

puts

test do |a, (b, c)|
p a
p b
p c
end

that demonstrated it pretty well
 

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,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top