Ruby块采用数组或多个参数 [英] Ruby block taking array or multiple parameters
问题描述
今天,我很惊讶地发现ruby会自动找到作为块参数给出的数组的值.
Today I was surprised to find ruby automatically find the values of an array given as a block parameter.
例如:
foo = "foo"
bar = "bar"
p foo.chars.zip(bar.chars).map { |pair| pair }.first #=> ["f", "b"]
p foo.chars.zip(bar.chars).map { |a, b| "#{a},#{b}" }.first #=> "f,b"
p foo.chars.zip(bar.chars).map { |a, b,c| "#{a},#{b},#{c}" }.first #=> "f,b,"
我希望最后两个示例会出现某种错误.
I would have expected the last two examples to give some sort of error.
- 这是红宝石中更笼统的概念的例子吗?
- 我不认为我在问题开头的措辞是正确的,我怎么称呼这里发生的事情?
推荐答案
Ruby的块机制对其有一个怪癖,也就是说,如果要遍历包含数组的内容,则可以将它们扩展为不同的变量:
Ruby's block mechanics have a quirk to them, that is if you're iterating over something that contains arrays you can expand them out into different variables:
[ %w[ a b ], %w[ c d ] ].each do |a, b|
puts 'a=%s b=%s' % [ a, b ]
end
此模式在使用Hash#each
时非常有用,并且您希望分解成对的key
和value
部分:each { |k,v| ... }
在Ruby代码中非常常见.
This pattern is very useful when using Hash#each
and you want to break out the key
and value
parts of the pair: each { |k,v| ... }
is very common in Ruby code.
如果您的块接受多个参数 ,并且要迭代的元素是一个数组,那么它将切换如何解释参数.您可以随时强制展开:
If your block takes more than one argument and the element being iterated is an array then it switches how the arguments are interpreted. You can always force-expand:
[ %w[ a b ], %w[ c d ] ].each do |(a, b)|
puts 'a=%s b=%s' % [ a, b ]
end
这对于复杂的情况很有用:
That's useful for cases where things are more complex:
[ %w[ a b ], %w[ c d ] ].each_with_index do |(a, b), i|
puts 'a=%s b=%s @ %d' % [ a, b, i ]
end
由于在这种情况下,它遍历数组和附加的元素,所以每个项目实际上都是内部为%w[ a b ], 0
形式的元组,如果您需要块仅接受一个参数.
Since in this case it's iterating over an array and another element that's tacked on, so each item is actually a tuple of the form %w[ a b ], 0
internally, which will be converted to an array if your block only accepts one argument.
这与定义变量时可以使用的原理大致相同:
This is much the same principle you can use when defining variables:
a, b = %w[ a b ]
a
# => 'a'
b
# => 'b'
这实际上为a
和b
分配了独立的值.与此相反:
That actually assigns independent values to a
and b
. Contrast with:
a, b = [ %w[ a b ] ]
a
# => [ 'a', 'b' ]
b
# => nil
这篇关于Ruby块采用数组或多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!