From: Jarmo Pertman Date: 2011-02-26T10:35:22+09:00 Subject: Re: Symbol#to_proc helping out with #select to beat Scala-s solution I still don't understand why modifying Enumerable didn't work, but i tried with Array instead and made this solution: class Array %w[select map sort_by].each {|m| class_eval %Q[alias_method :_#{m}, m; def #{m}█ _#{m} {|x| x.instance_eval &block} end]} end That allows me to write the example above like this: sales.select{value > 50000}.map{buyer}.sort_by{age} It's not too bad, i think. I mean, it's not less readable as it is with regular block/&: syntax. Jarmo On Feb 26, 2:51 am, Jarmo Pertman wrote: > I tried to modify the methods directly in Enumerable and succeeded > only 50%. > > Consider the code below: > module Enumerable >   def select >     puts 1 >   end > end > > class Array >   include Enumerable > end > > [2,3].select # doesn't print 1 > > If i use find_all instead then it works: > module Enumerable >   def find_all >     puts 1 >   end > end > > class Array >   include Enumerable > end > > [2,3].find_all # prints 1 > > Now i'm confused as to why isn't #select working as i was hoping for? > > Jarmo > > On Feb 26, 1:43 am, Sean O'Halpin wrote: > > > > > > > > > [snip] > > > > I'm thinking that one possible way to shorten my calls would be to use > > > instance-eval in #select, #map and #sort_by so i could do it like > > > this: > > > sales.select{value > 50000}.map{buyer}.sort_by{age} > > > Here's a trivial implementation of that idea: > > > module Relational > >   def project(&block) > >     map { |x| x.instance_eval(&block) } > >   end > > >   def where(&block) > >     select { |x| x.instance_eval(&block) } > >   end > > >   def order_by(&block) > >     sort_by { |x| x.instance_eval(&block) } > >   end > > end > > > class Buyer < Struct.new(:name, :age) > > end > > > class Sale < Struct.new(:value, :buyer) > > end > > > alice = Buyer["Alice", 30] > > bob = Buyer["Bob", 40] > > charlie = Buyer["Charlie", 50] > > > sales = [ > >          Sale[80000, alice], > >          Sale[40000, bob], > >          Sale[60000, charlie], > >         ] > > > class Array > >   include Relational > > end > > > p sales.where{ value > 50000 }.project{ buyer }.order_by{ age } > > # => [#, # > name="Charlie", age=50>] > > > # But it becomes uglier when you want to do this: > > p sales.where{ value > 50000 }.project{ [value, buyer] }.order_by{ self[1].age } > > # => [[60000, #], [80000, # > Buyer name="Charlie", age=50>]] > > > # Better to do it this way round: > > p sales.where{ value > 50000 }.order_by{ buyer.age }.project{ [value, buyer] } > > # => [[60000, #], [80000, # > Buyer name="Charlie", age=50>]] > > > However, in practice, I don't use it. Ruby's block syntax is perfectly > > elegant as it is. Why not be content with it? > > > Regards, > > Sean