Ruby/Hash/Hash Extensions
Материал из Wiki.crossplatform.ru
Содержание |
Add method hash class to invert a hash: turn value to key
class Hash def safe_invert new_hash = {} self.each do |k,v| if v.is_a? Array v.each { |x| new_hash.add_or_append(x, k) } else new_hash.add_or_append(v, k) end end return new_hash end def add_or_append(key, value) if has_key?(key) self[key] = [value, self[key]].flatten else self[key] = value end end end phone_directory = { "A" => "1", "B" => "2", "M" => "3" } p phone_directory.safe_invert p phone_directory.safe_invert.safe_invert
Add method to Hash class to remove one hash from another
class Hash def remove_hash(other_hash) delete_if { |k,v| other_hash[k] == v } end end squares = { 1 => 1, 2 => 4, 3 => 9 } doubles = { 1 => 2, 2 => 4, 3 => 6 } squares.remove_hash(doubles) squares # => {1=>1, 3=>9}
Find all
class Hash def find_all new_hash = Hash.new each { |k,v| new_hash[k] = v if yield(k, v) } new_hash end end squares = {0=>0, 1=>1, 2=>4, 3=>9} squares.find_all { |key, value| key > 1 } # => {2=>4, 3=>9}
Grep a hash
class Hash def grep(pattern) inject([]) do |res, kv| res << kv if kv[0] =~ pattern or kv[1] =~ pattern res end end end h = { "apple tree" => "plant", "ficus" => "plant", "shrew" => "animal", "plesiosaur" => "animal" } p h.grep(/pl/) p h.grep(/plant/) # => [["ficus", "plant"], ["apple tree", "plant"]] p h.grep(/i.*u/) # => [["ficus", "plant"], ["plesiosaur", "animal"]]