The Code Kitchen

Further #to_proc Abuse

Everybody loves to abuse #to_proc. The Symbol#to_proc extension has even been baked in to Ruby 1.9.

Why not continue the duck typing abuse? Let's build a cheap ActiveRecord knock-off for Enumerable:

my_peeps.find_all(&{:last_name => "Palmer"})  appointments.find_all(&{:description => /billable/i, :time => (start_time..end_time)})  my_socks.any?(&{:status => 'washed'}) 

The implementation is simple.

class Hash; def to_proc   proc { |obj| self.inject(true) { |m,(k,v)| m && v === obj.send(k) } } end; end 

Of course, I wouldn't try to argue that it's as useful as Symbol#to_proc. Fun to play with, though. I'm using it in a RubyOSA script that I'm building for Colleen. For completeness, this version performs a little better if the hash has many terms and a lot of records will be filtered out:

class Hash; def to_proc     proc { |obj| self.inject(nil) { |_,(k,v)| v === obj.send(k) || (break false) } } end; end 

Comments? Feedback? Drop me a line.

The Code Kitchen is a software consulting business run by me, Brian Palmer. But this site is really about whatever catches my interest.

Questions or Feedback? Email Brian.

Macadamia Cookies

cookiesLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

go to recipe