Notes posted by guyboertje
RSS feed
guyboertje -
May 17, 2010
2 thanks
Add has_keys? method to Hash class
class Hash
def has_keys?(*_keys) (_keys - self.keys).empty? end
end
h = {1=>‘a’,2=>‘b’}
h.has_keys?(1,2) #-> true
h.has_keys?(1,3) #-> false
guyboertje -
March 17, 2010 - (>= v1_8_7_72)
0 thanks
Create new Hash as subset of another
old_hash = {:a=>‘A’,:b=>‘B’,:c=>‘C’,:d=>‘D’,:e=>‘E’,:f=>‘F’}
only_keys = [:a,:c,:f]
new_hash = Hash[*old_hash.find_all{|k,v| only_keys.member?(k)}.flatten]
# => {:a=>“A”, :c=>“C”, :f=>“F”}
or for values
only_vals = [‘A’,‘D’,‘G’]
new_hash = Hash[*old_hash.find_all{|k,v| only_vals.member?(v)}.flatten]
# => {:a=>“A”, :d=>“D”}