How does iteration work in Ruby?

I recently started coding for Ruby, and I am having problems with block parameters. Take the following code, for example:

h = { # A hash that maps number names to digits
:one => 1, # The "arrows" show mappings: key=>value
:two => 2 # The colons indicate Symbol literals
}
h[:one] # => 1. Access a value by key
h[:three] = 3 # Add a new key/value pair to the hash
h.each 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; "

I understand the general hash functionality, but I don’t understand how valueand keyinstalled on anything. They are set as parameters in the block, but the hash is never associated in any way with these parameters.

+5
source share
5 answers

This is the syntax of the Ruby block (Ruby name for anonymous function). And key, value- this is nothing but the arguments passed to the anonymous function.

Hash#eachtakes one parameter: a function that has 2 parameters, keyand value.

, , : h.each each h. :

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; 

- , each , key, value - , . , , , , , - .

. :

 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

, :

print_key_value = lambda{|arg1, arg2| print "#{arg1}:#{arg2}"}
h = { 
  :one => 1,
  :two => 2
}

h.each &print_key_value

:

  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)
+6

(h) - , h.each, each . : " / h, key , value , ."

, each... , , , . (, . Ruby.)

+6

, h.each :

h.each < - ,

, , :

a = [1,2,3]
a.each do |v|
  puts v
end

(each, each_with_index,...)

+1

h.each, , - h, . , , value key , .

0

, . . . |...| each {...} . name key value , . .

each{|k, v| ...}  # k is key, v is value
each{|a, b| ...}  # a is key, b is value

:

each{|value, key| ...} # value is key, key is value
0

All Articles