From: MonkeeSage Date: 2007-11-30T15:10:03+09:00 Subject: Re: hash.clear("value") On Nov 29, 4:35 am, Robert Klemme wrote: > 2007/11/28, MonkeeSage : > > > > > On Nov 28, 1:47 pm, Andrew Stone wrote: > > > Note: parts of this message were removed by the gateway to make it a legal Usenet post. > > > > Hello all, > > > > Was just wondering if there was something simple like: > > > > hash.clear("value") > > > > This would remove all entries from the hash whose value == "value". > > > > Yeah, I know about delete_if, this would just be more succinct. I can be > > > lazy sometimes. > > > > thanks, > > > andy > > > > -- > > > Andrew Stone > > > You can always wrap delete_if... > > > class Hash > > def remove(target) > > self.delete_if { | key, value | > > value == target > > } > > end > > end > > Just a subtle point: IMHO it is better to put "target" on the left > side of the comparison because that gives the caller more control on > the deletion criterion: > > class Hash > def remove(target) > delete_if { | key, value | > target == value > } > end > end > > For example, you could do > > crit = Object.new > def crit.==(x) x < 10 end > a_hash.remove crit # remove all entries where value is < 10 Nice. :) > It's a similar pattern to how "case" does comparison via "===". But > then again, this is probably even better: > > class Hash > def remove_val > delete_if {|k,v| yield v} > self > end > end > > Because it's more modular. But then again, you can use delete_if directly. :-) Yes, but we're lazy! ;) No blocks here! Heh. Otherwise we would just use delete_if! ;) > Kind regards > > robert > > -- > use.inject do |as, often| as.you_can - without end