[英]Iterate over array of arrays
之前曾有人问过这个问题,但我找不到有效的答案。 我有以下代码:
[[13,14,16,11],[22,23]].each do |key,value|
puts key
end
理论上应该打印:
0
1
但是,它打印:
13
22
为什么红宝石会表现这种方式?
为什么红宝石会表现这种方式?
这是因为当each
迭代器和其他迭代器与一个块而不是一个lambda一起使用时,内部实际发生的事情实际上更接近于此:
do |key, value, *rest|
puts key
end
考虑以下代码以说明:
p = proc do |key,value|
puts key
end
l = lambda do |key,value|
puts key
end
使用以上内容,以下将分别将(key, value)
为(13, 14)
和(22, 23)
,并且在第一种情况下上述*rest
为[16, 11]
( rest
将被丢弃) :
[[13,14,16,11],[22,23]].each(&p)
相比之下,以下内容会吐出一个参数错误,因为lambda(类似于块,但出于Arity的考虑除外)将接收完整的数组作为参数(因为参数数量,所以上面没有*rest
严格执行):
[[13,14,16,11],[22,23]].each(&l) # wrong number of arguments (1 for 2)
为了获得适合您情况的索引,您需要在其他答案中突出显示each_with_index
。
相关讨论:
您可以使用Array
的each_index' method which returns the index of the element instead of the element itself. See [Ruby's
each_index' method which returns the index of the element instead of the element itself. See [Ruby's
更多信息, each_index' method which returns the index of the element instead of the element itself. See [Ruby's
Array的文档] 1 。
您有一个数组数组-称为二维数组。
在循环中,将“值”变量分配给第一个数组[13,14,16,11]
当您尝试puts
“值”变量时,它仅返回第一个元素13。
尝试将puts value
更改为puts value.to_s
,它将数组转换为字符串。
如果需要每个值,则在代码中添加另一个循环块,以循环遍历“值”变量中的每个元素。
[[1,2,3],['a','b','c']].each do |key,value|
value.each do |key2,value2|
puts value2
end
end
当您这样做时:
[[13,14,16,11],[22,23]].each do |key,value|
在第一次迭代完成之前,先进行分配:
key, value = [13,14,16,11]
这样的赋值将导致key
为13, value
14。相反,应使用each_with_index do |array, index|
。 这会将作业更改为:
array, index = [[13,14,16,11], 0]
这将导致array
为[13,14,16,11]且index
为0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.