Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is the Ruby block (Ruby's name for an anonymous function) syntax. And <code>key</code>, <code>value</code> are nothing but the arguments passed to the anonymous function. </p> <p><code>Hash#each</code> takes one parameter: A function which has 2 parameters, <code>key</code> and <code>value</code>.</p> <p>So if we break it down into parts, this part of your code: <code>h.each</code>, is calling the <code>each</code> function on <code>h</code>. And this part of your code:</p> <pre><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; </code></pre> <p>is the function passed to <code>each</code> as an argument and <code>key</code>, <code>value</code> are arguments passed to this function. It doesn't matter what you name them, first argument expected is <em>key</em> and second argument expected is <em>value</em>.</p> <p>Lets draw some analogies. Consider a basic function:</p> <pre><code> 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 </code></pre> <p>So your code can also be written as:</p> <pre><code>print_key_value = lambda{|arg1, arg2| print "#{arg1}:#{arg2}"} h = { :one =&gt; 1, :two =&gt; 2 } h.each &amp;print_key_value </code></pre> <p>There are multiple ways in which the code inside a block can be executed:</p> <pre><code> 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) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload