2011-08-16 39 views
12

我正在使用Rails 3.0。我有一個二維數組。二維數組由用戶數據和布爾值組成。如何從軌道3中的二維數組數組中找到記錄?

例如:[ [user1,true], [user2,true], [user3,false] ]

它看起來是這樣的:

[ 
    [#<User id: 1, email: "[email protected]", username: "abc">, true], 
    [#<User id: 2, email: "[email protected]", username: "ijk">, true], 
    [#<User id: 3, email: "[email protected]", username: "xyz">, false], 
] 

我想找/提取記錄條件;說找到一整行User id=2,它應該只返回第二行,即[#<User id: 2, email: "[email protected]", username: "ijk">, true]

有反正循環這樣的數組嗎?如何實現?

+0

這是一個簡單的循環;你試過什麼了?順便說一句,你是想僅僅使用內存數組來做到這一點,還是你的目標是高效並只從數據庫加載該記錄? – Zabba

+0

它應該只能有效地抓取一條記錄..我正在檢查以下解決方案... – Bongs

回答

23
my_array.select{ |user, flag| user.id == 2} 

所有用戶真正的標誌:

my_array.select{ |user, flag| flag } 

或假:

my_array.select{ |user, flag| !flag } 
+1

我是新來的,但令人驚訝的是,當我嘗試第一個命令'@m.select {| user,flag | user.id == 2}'它返回了所有的三條記錄。所以,而不是'選擇'我使用'檢測',它的工作。其他兩個命令'@ m.select {| user,flag |標誌}'和'@ m.select {| user,flag | !flag}'工作得很好。謝謝... – Bongs

+0

看起來像你嘗試'@ m.select {| user,flag | user.id = 2}'或者全部關閉它們的ID = 2 – fl00r

+0

你是對的......某種程度上,id被設置爲2以表示所有的記錄..謝謝... – Bongs

11

你可以做這樣的事情

[ [user1,true], [user2,true], [user3,false] ].select { |u| u.first.id == 2} 

這將只返回有用戶ID等於2

+0

'@ m.select {| u | u.first.id == 2}'返回所有記錄。但是當我將它改爲'@ m.detect {| u | u.first.id == 2}'它只返回一條記錄。我是新手。你能告訴我爲什麼這樣嗎? – Bongs

+0

我發現了這個問題。不知怎的,ID設置爲2的所有三個記錄... – Bongs

9

相同的答案@eugen,只有語法差異(和使用檢測到返回記錄一維陣列,而不是2維陣列):

[ [user1,true], [user2,true], [user3,false] ].detect { |user, boolean| user.id == 2 } 
=> [user2, true] 
+0

謝謝...'檢測'完全按預期工作... – Bongs