简体   繁体   中英

In an array of hash how to delete an element with particular value for a key in ruby?

In an array of hash how to delete an element with particular value for a key?

For example:

array = [ {"lang"=> 'Ruby', "is_using"=> "Yes"}, { "lang"=> "Go", "is_using" => "No"}, {"lang"=> "Rust", "is_using"=> "No"} ]

I need to write a minimal and efficient ruby script which deletes all the elements from the array which has "No" as a value for the key "is_using".

Use Array#delete_if :

array = [ {"lang"=> 'Ruby', "is_using"=> "Yes"}, { "lang"=> "Go", "is_using" => "No"}, {"lang"=> "Rust", "is_using"=> "No"} ]
array.delete_if { |hash| hash['is_using'] == 'No' }
#=> [{ "lang" => "Ruby", "is_using" => "Yes" }]

If you don't want to mutate the original array, then you could use reject :

array = [{ "lang"=> 'Ruby', "is_using"=> "Yes" },
         { "lang"=> "Go", "is_using" => "No" },
         { "lang"=> "Rust", "is_using"=> "No" }]

array.reject { |h| h["is_using"].eql?('Yes') }
# [{"lang"=>"Go", "is_using"=>"No"}, {"lang"=>"Rust", "is_using"=>"No"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM