Robert Dober
6/10/2007 12:05:00 PM
On 6/10/07, Robert Klemme <shortcutter@googlemail.com> wrote:
>
> A funny (and readable) way to test collection sizes just occurred to me:
>
> irb(main):001:0> class Integer
> irb(main):002:1> def elements
> irb(main):003:2> cond = lambda {|enum| self == enum.size}
> irb(main):004:2> class <<cond
> irb(main):005:3> alias :=== :call
> irb(main):006:3> end
> irb(main):007:2> cond
> irb(main):008:2> end
> irb(main):009:1> end
> => nil
> irb(main):010:0> case [1,2,3]
> irb(main):011:1> when 3.elements
> irb(main):012:1> puts "three!"
> irb(main):013:1> when 5.elements
> irb(main):014:1> puts "too much!"
> irb(main):015:1> else
> irb(main):016:1* puts "else"
> irb(main):017:1> end
> three!
> => nil
>
> :-)
>
> Kind regards
>
> robert
>
>
As I said, this is really cool, now here comes a first quick hack of
generalization, you gotta file an RCR for this ;)
Please note the absence of "@" in my code ;)
class Module
def define_casey args={}
arg_mth = args[:on]
name = args[:name]
trans = args[:transform]
define_method name do
cond = lambda{ |x|
trans ? self.send(trans) == x.send( arg_mth ) :
self == x.send( arg_mth )
}
class << cond
alias_method :===, :call
end
cond
end
end
end
class Integer
define_casey :on => :size, :name => :elements
end
case []
when 0.elements
puts :empty
end
What you think?
Cheers
Robert
--
You see things; and you say Why?
But I dream things that never were; and I say Why not?
-- George Bernard Shaw