Ruby 获取二维数组中值的坐标
我想得到存储在数组中的对象的每次出现的坐标。如果我有一个数组:Ruby 获取二维数组中值的坐标,ruby,arrays,Ruby,Arrays,我想得到存储在数组中的对象的每次出现的坐标。如果我有一个数组: array = [["foo", "bar", "lobster"], ["camel", "trombone", "foo"]] 还有一个对象“foo”,我想得到: [[0,0], [1,2]] 下面的内容可以做到这一点,但它是精心设计的,丑陋的: array.map .with_index{ |row,row_index| row.map.with_index { |v,col_index| v=="foo" ?
array = [["foo", "bar", "lobster"], ["camel", "trombone", "foo"]]
还有一个对象“foo”
,我想得到:
[[0,0], [1,2]]
下面的内容可以做到这一点,但它是精心设计的,丑陋的:
array.map
.with_index{
|row,row_index| row.map.with_index {
|v,col_index| v=="foo" ? [row_index,col_index] : v
}
}
.flatten(1).find_all {|x| x.class==Array}
有没有更直接的方法?这是以前的,产生了一个类似的不雅观的解决方案。这里有一个稍微优雅一点的解决方案。我有:
- 使用了
而不是flat\u map
flatten
- 使用
而不是。每个_索引。选择
,然后必须在末尾剥离非数组,这真的很难看.map。使用_索引
- 添加缩进
这里有一个稍微优雅一点的解决方案。我有:
- 使用了
而不是flat\u map
flatten
- 使用
而不是。每个_索引。选择
,然后必须在末尾剥离非数组,这真的很难看.map。使用_索引
- 添加缩进
最好使用平面阵列
cycle = array.first.length
#=> 3
array.flatten.to_enum.with_index
.select{|e, i| e == "foo"}
.map{|e, i| i.divmod(cycle)}
#=> [[0, 0], [1, 2]]
或
最好使用平面阵列
cycle = array.first.length
#=> 3
array.flatten.to_enum.with_index
.select{|e, i| e == "foo"}
.map{|e, i| i.divmod(cycle)}
#=> [[0, 0], [1, 2]]
或
另一种方式:
array = [["foo", "bar", "lobster"], ["camel", "trombone", "foo"],
["goat", "car", "hog"], ["foo", "harp", "foo"]]
array.each_with_index.with_object([]) { |(a,i),b|
a.each_with_index { |s,j| b << [i,j] if s == "foo" } }
#=> [[0,0], [1,2], [3,0], [3,2]
array=[[“foo”、“bar”、“lobster”]、[“camel”、“trombone”、“foo”],
[“山羊”、“汽车”、“猪”]、[“福”、“竖琴”、“福”]]
数组。每个_与_索引。与_对象([]){|(a,i),b|
a、 指数为{s,j | b[[0,0],[1,2],[3,0],[3,2]的每个|u
另一种方式:
array = [["foo", "bar", "lobster"], ["camel", "trombone", "foo"],
["goat", "car", "hog"], ["foo", "harp", "foo"]]
array.each_with_index.with_object([]) { |(a,i),b|
a.each_with_index { |s,j| b << [i,j] if s == "foo" } }
#=> [[0,0], [1,2], [3,0], [3,2]
array=[[“foo”、“bar”、“lobster”]、[“camel”、“trombone”、“foo”],
[“山羊”、“汽车”、“猪”]、[“福”、“竖琴”、“福”]]
数组。每个_与_索引。与_对象([]){|(a,i),b|
a、 每个带\u索引{s,j | b[[0,0],[1,2]、[3,0]、[3,2]