Ruby的新手;当我使用数组时,两者之间是有区别的,Enumerable#each_with_index
并且Array#index
我一直在使用多维数组来尝试查找给定值的位置。当我使用任一代码时,我的代码都能通过所有测试。坐标是我用来保存给定值位置的数组(在本例中为1)
field=[[1,0],[0,0]]
coordinates=[]
field.each_with_index do |item|
if item.index(1)
coordinates.push(field.index(item)).push(item.index(1))
end
end
在此先感谢您的帮助。
让我们仔细看看您的代码:
field=[[1,0],[0,0]]
coordindates = []
field.each_with_index do |item|
if item.index(1)
coordinates.push(field.index(item)).push(item.index(1))
end
end
让:
enum = field.each_with_index
#=> #<Enumerator: [[1, 0], [0, 0]]:each_with_index>
如您所见,这将返回一个枚举数。
Ruby看到这样的代码:
enum.each do |item|
if item.index(1)
coordinates.push(field.index(item)).push(item.index(1))
end
end
枚举数的元素将由Enumerator#each传递到块中,由于接收者是class的实例,因此它将调用Array#each。field
Array
enum
通过将其转换为数组,我们可以看到的元素:
enum.to_a
#=> [[[1, 0], 0], [[0, 0], 1]]
如您所见,它有两个元素,每个元素都是两个元素的数组,第一个是两个整数的数组,第二个是整数。
我们可以模拟的操作each
通过发送枚举#旁边来enum
和分配块变量返回的值next
。因为只有一个块变量item
,所以我们有:
item = enum.next
#=> [[1, 0], 0]
那很可能既不是您的期望,也不是您想要的。
接下来,您调用数组#指数上item
:
item.index(1)
#=> nil
index
在数组中搜索item
等于的元素1
。如果找到一个,则返回该元素在数组中的索引。(例如,item.index(0) #=> 1
)。既不[1,0]
也不是0
平等的1
,index
回报nil
。
让我们倒带(并重新创建枚举器)。您需要两个块变量:
field.each_with_index do |item, index|...
与以下内容相同:
enum.each do |item, index|...
所以现在:
item, index = enum.next
#=> [[1, 0], 0]
item #=> [1, 0]
index #=> 0
和
item.index(1)
#=> 0
我会让你从这里拿走,但我只想提一件事。我不主张这样做,但是您可以写:
field.each_with_index do |(first, second), index|...
在这种情况下:
(first, second), index = enum.next
#=> [[1, 0], 0]
first #=> 1
second #=> 0
index #=> 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句