Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在嵌套数组中查找对象的位置_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 在嵌套数组中查找对象的位置

Ruby on rails 在嵌套数组中查找对象的位置,ruby-on-rails,ruby,Ruby On Rails,Ruby,在下面的数组中,如何找到id=71的产品的位置 [[[#<Product id: 71>, #<BigDecimal:x>], 0], [[#<Product id: 73>, #<BigDecimal:x>], 1]] 或者,如果我有@product=product.find(71),那么我将如何发现该对象与上述数组中的编号0关联,而不是1?可以使用array#index进行块、块参数解构(这里使用符号而不是自定义对象): 如果您对特定元素

在下面的数组中,如何找到id=71的产品的位置

[[[#<Product id: 71>, #<BigDecimal:x>], 0], [[#<Product id: 73>, #<BigDecimal:x>], 1]]

或者,如果我有
@product=product.find(71)
,那么我将如何发现该对象与上述数组中的编号
0
关联,而不是
1

可以使用
array#index
进行块、块参数解构(这里使用符号而不是自定义对象):

如果您对特定元素感兴趣,而不是对其索引感兴趣,只需使用
find
而不是
index
(块参数将是相同的)。

您可以使用
Array#index
进行块、块参数解构(此处使用符号而不是自定义对象):

如果您对特定元素感兴趣,而不是它的索引,只需使用
find
而不是
index
(块参数将是相同的)

arr = [[[:a, :b], 5], [[:c, :d], 7]]
# => [[[:a, :b], 5], [[:c, :d], 7]] 
arr.index{|((a, b), c)| c == 7}
# => 1 
arr.index{|((a, b), c)| b == :a}
# => nil 
arr.index{|((a, b), c)| b == :b}
# => 0