从rails中的哈希数组中删除哈希

时间:2018-02-16 06:30:16

标签: ruby-on-rails arrays ruby-on-rails-3 hash ruby-hash

我有json格式的哈希数组,我必须从该数组中删除一个哈希,我正在迭代该数组,如果该特定键/值匹配,我正在删除该哈希, 我找到了clear()方法但是,明确留下{},我不需要 我希望删除整个哈希

[{"question":"0a2a3452","answer":"lopq"},
 {"question":"58deacf9","answer":"admirationo"},
 {"question":"32c53e","answer":"acion"},
 {"question":"b5546bcf","answer":"figure"},
 {"question":"4f246a10","answer":"zelta"},
 {"question":"bf546c04","answer":"deltaa"}]

即如果我的密钥匹配为“0a2a3452”,我想删除第一个哈希

2 个答案:

答案 0 :(得分:1)

您可以使用delete_if方法:

arr = [{"question":"0a2a3452","answer":"lopq"},
       {"question":"58deacf9","answer":"admirationo"},
       {"question":"32c53e","answer":"acion"},
       {"question":"b5546bcf","answer":"figure"},
       {"question":"4f246a10","answer":"zelta"},
       {"question":"bf546c04","answer":"deltaa"}]

arr.delete_if {|a| a[:question] == '0a2a3452' }

答案 1 :(得分:0)

试试这个:

items = [
  {"question":"0a2a3452","answer":"lopq"},
  {"question":"58deacf9","answer":"admirationo"},
  {"question":"32c53e","answer":"acion"},
  {"question":"b5546bcf","answer":"figure"},
  {"question":"4f246a10","answer":"zelta"},
  {"question":"bf546c04","answer":"deltaa"}
]

items = items.reject {|i| i[:question] == '0a2a3452'}