0

I have array of hashes in json format, and I have to remove one of the hash from that array, I am iterating that array and if that particular key/ value matches i am deleting that hash, I found clear() method but, clear leaves the {}, which I don't require I want the whole hash to be removed

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

i.e if my key matches as "0a2a3452", I want to delete the first hash

Hamdi Bayhan
  • 1,773
  • 4
  • 17
  • 20
summu
  • 388
  • 2
  • 7
  • 25

2 Answers2

2

You can do with delete_if method:

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' }
Hamdi Bayhan
  • 1,773
  • 4
  • 17
  • 20
1

Try this:

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'}
Tallboy
  • 12,847
  • 13
  • 82
  • 173