This is the Ruby block (Ruby's name for an anonymous function) syntax. And key
, value
are nothing but the arguments passed to the anonymous function.
Hash#each
takes one parameter: A function which has 2 parameters, key
and value
.
So if we break it down into parts, this part of your code: h.each
, is calling the each
function on h
. And this part of your code:
do |key, value| # Iterate through the key/value pairs
print "#{value}:#{key}; " # Note variables substituted into string
end # Prints "1:one; 2:two; 3:three;
is the function passed to each
as an argument and key
, value
are arguments passed to this function. It doesn't matter what you name them, first argument expected is key and second argument expected is value.
Lets draw some analogies. Consider a basic function:
def name_of_function(arg1, arg1)
# Do stuff
end
# You'd call it such:
foo.name_of_function bar, baz # bar is becomes as arg1, baz becomes arg2
# As a block:
ooga = lambda { |arg1, arg2|
# Do stuff
}
# Note that this is exactly same as:
ooga = lambda do |arg1, arg2|
# Do stuff
end
# You would call it such:
ooga.call(bar, baz) # bar is becomes as arg1, baz becomes arg2
So your code can also be written as:
print_key_value = lambda{|arg1, arg2| print "#{arg1}:#{arg2}"}
h = {
:one => 1,
:two => 2
}
h.each &print_key_value
There are multiple ways in which the code inside a block can be executed:
yield
yield key, value # This is one possible way in which Hash#each can use a block
yield item
block.call
block.call(key, value) # This is another way in which Hash#each can use a block
block.call(item)
h.each do |key,value|
the association ofkey,value
toh
for the entiredo
block is defined on that line. The nameskey
andvalue
could be whatever you like. – Fareesh Vijayarangamh.each
looks too magical for then you could always useh.each_pair
. – Jonas Elfströmirb
. It lets you easily start playing with variables and assignments. It's a great tool when you want to learn these sorts of things. – the Tin Man