Ruby/Hash/delete if
Материал из Wiki.crossplatform.ru
Содержание |
Delete if for a certain value
myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" } myHash.delete_if { |key, value| value == "Two" } # => {5=>"Five", 1=>"One", 3=>"Three", 4=>"Four"}
delete_if passes all pairs into the block, so you can delete based on a key or a value.
# Here is an example of a deletion based on value: myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" } myHash.delete_if { |key, value| value == "Two" } # => {5=>"Five", 1=>"One", 3=>"Three", 4=>"Four"}
delete_if uses a block
# It removes the key-values from the hash for which the block evaluates to true. myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" } # With delete_if, I"ll remove all pairs whose key values are less than 3: myHash.delete_if { |key, value| key < 3 }
Delete if with block logics
myHash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" } myHash.delete_if { |key, value| key < 3 } # => {5=>"Five", 3=>"Three", 4=>"Four"}
Deleting Hash Elements Conditionally
x = { "a" => 100, "b" => 20 } x.delete_if { |key, value| value < 25 } puts x.inspect