2014-09-12 4 views
1

배열의 배열에 저장된 모든 오브젝트의 좌표를 가져 오려고합니다. 내가 배열이있는 경우 :2D 배열에서 값의 좌표를 얻습니다.

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} 

인가 이 작업을 수행하는 더 간단한 방법이 있습니까? 이것은 이전에 asked이었고, 비슷한 우아하지 않은 해결책을 만들어 냈습니다.

답변

4

다음은 좀 더 우아한 해결책입니다. 내가 가진 :

  • 대신 .map.with_index.each_index.select을 사용하는 말
  • 에 보내고 다음
  • 추가 들여 쓰기를
정말 추한 말에 비 배열을 제거하는 데 flat_map 대신 flatten을 사용
array.flat_map.with_index {|row, row_idx| 
    row.each_index.select{|i| row[i] == 'foo' }.map{|col_idx| [row_idx, col_idx] } 
} 
0

플랫 어레이로 작업하는 것이 좋습니다.

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 = array.flatten 
array.each_index.select{|i| array[i] == "foo"}.map{|e, i| i.divmod(cycle)} 
#=> [[0, 0], [1, 2]] 
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] 
관련 문제