迭代如何在Ruby中工作?

时间:2011-03-22 07:32:57

标签: ruby loops block

我最近开始编写Ruby,我对块参数有误解。 以下面的代码为例:

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; "

我了解常规哈希功能,但我不明白valuekey如何设置为任何内容。它们被指定为块中的参数,但是哈希永远不会以任何方式与这些参数相关联。

5 个答案:

答案 0 :(得分:6)

由于您调用h而不是在其他内容上调用h.each,哈希(each)与循环相关联。它有效地说,“对于h中的每个键/值对,让key迭代变量成为键,让value迭代变量为值,然后执行循环“。

如果这没有帮助,请查看this page on each ...如果您可以解释更多关于您觉得棘手的问题,我们可能会提供更多帮助。 (好吧,其他人也许可以。我真的不懂Ruby。)

答案 1 :(得分:6)

这是Ruby块(Ruby的匿名函数名称)语法。而keyvalue只不过是传递给匿名函数的参数。

Hash#each有一个参数:一个包含2个参数keyvalue的函数。

因此,如果我们将其细分为部分内容,则代码的这一部分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的函数,keyvalue是传递给此函数的参数。你命名它们并不重要,第一个参数是 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)

答案 2 :(得分:1)

散列确实与这些参数相关联,因为您调用h.each来遍历散列:

h.each< - 这是您缺少的链接

如果你开始使用数组,也许对你来说更容易:

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

并首先使用此eacheach_with_index,...)

答案 3 :(得分:0)

当你调用h.each时,就是说你想要在每次迭代中使用这个特定的h哈希值。 因此,当您这样做时,valuekey变量将逐个分配给哈希值。

答案 4 :(得分:0)

我认为问题在于变量名称。名字没有意义。只有订单才有意义。在|...|each {...}内,键和值按此顺序给出。由于将变量名称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