2016-08-15 55 views
1

我想比較一個字符串與對象數組。所以當一個字符串值與數組中的那個對象匹配時,它會保留它。ruby​​ keep_if數組與字符串的比較

這裏是例子:

sample = [#<Model::ID:0x007fcb83ace8a0 
    type_id: 6, 
    parent_name: "Old Man", 
    child_name: "Junior">, 
#<Model::ID:0x007fcb83abd0a0 
    type_id: 6, 
    parent_name: "Mary", 
    child_name: "Michelle">, 
#<Model::ID:0x007fcb83abce70 
    type_id: 6, 
    parent_name: "Ole Bob", 
    child_name: "Bobby">] 

name = "Michelle" 

所以我試過如下:

sample.keep_if { |keep_ele| [keep_ele]["child_name"] == name } 

,這將返回以下錯誤: 類型錯誤:字符串的隱式轉換成整數

但是當我在IRB中輸出sample[1]["child_name"]時,它等於"Michelle"

於是我嘗試:

sample.keep_if { |keep_ele| keep_ele["child_name"] == name } 

,它只是返回一個空數組:[]

如何運行keep_if任何想法?

回答

4

keep_ele裏面的keep_if塊已經是數組中的模型對象(item)。你應該使用下面的對比,而不是:

sample.keep_if { |keep_ele| keep_ele["child_name"] == name } 

看看文檔頁面Array#keep_if。這裏是類似的例子:

sample = [ 
    { 
    "child_name" => "Mike" 
    }, { 
    "child_name" => "Michelle" 
    }, { 
    "child_name" => "Joe" 
    } 
] 

name = "Michelle" 
puts sample.keep_if { |keep_ele| keep_ele["child_name"] == name } 
# => {"child_name"=>"Michelle"}