2012-03-16 161 views
0

我有一個嵌套陣列看起來像這樣:紅寶石嵌套陣列

@nested = [ 
    ['1','2','3'], 
    ['1','5','9'], 
    ['1','4','7'], 
    ['3','5','7'], 
    ['3','6','9'], 
    ['7','8','9'], 
    ['4','5','6'], 
    ['2','5','8'] 
] 

我想採取任何整數(即1..9)的用戶輸入,並找到每一個,其具有輸入數組整數。

不知道該怎麼做。

回答

8

使用select

num_to_search = "9" 
@nested.select do |array| 
    array.include? num_to_search 
end 
#=> [["1", "5", "9"], ["3", "6", "9"], ["7", "8", "9"]] 
+0

我只好把'如果array.include(num_to_search)提出array.inspect end'讓你的輸出?原來給了我一連串的「真/假」。目前,我堅持使用Ruby 1.8.7。這是原因嗎? – ScottJShea 2012-03-16 22:59:06

+0

+1 for .select(條件)over .map(每個條目) – 2012-03-16 23:01:09

+0

@ScottJShea它不應該打印任何東西,它應該返回該數組數組。我剛剛證實,返回值是我在Ruby 1.8.7和1.9.3的答案中顯示的。 – 2012-03-16 23:01:47