From: tilde Date: 2010-09-03T17:50:08+09:00 Subject: Re: case (variable) when type1 ... when type2 ... end On 09/03/10 09:49, tilde wrote: > On 09/03/10 09:07, Robert Klemme wrote: >> On Fri, Sep 3, 2010 at 7:25 AM, tilde wrote: >>> On 08/30/10 10:33, Jean-Julien Fleck wrote: >>>>> >>>>> how can I write case statement to check of specific type the variable >>>>> has? >>>>> Something like: >>>> >>>> It simpler: >>>> >>>>> case var >>>>> when :Fixnum >>>>> puts "#{var} is Fixnum" >>>>> when :String >>>>> puts "#{var} is String" >>>>> end >>>> >>>> case var >>>> when Fixnum >>>> puts "#{var} is Fixnum" >>>> when String >>>> puts "#{var} is String" >>>> end >>>> >>>> (no ":") >>>> >>>> Cheers, >>>> >>> >>> Hi, could you explain me why this works? It's a special behaviour of the >>> "case" statment? >> >> "case" uses operator "===" to check conditions. If you do "case x >> when y" then "y === x" is invoked to check the condition (note the >> order of x and y). You can even cook your own >> >> positive = lambda {|x| x>= 0} >> class<< positive >> alias :=== :call >> end >> >> (-4..4).each do |i| >> case i >> when positive >> puts "#{i} pos" >> else >> puts "#{i} neg" >> end >> end >> >> btw, there is also another form of case >> >> case # no value here! >> when i>= 0 >> puts "#{i} pos" >> else >> puts "#{i} neg" >> end >> >> Kind regards >> >> robert >> > Clear yet concise explaination, thank you! Also (at least in 1.9.2) the alias is unnecessary, if a proc is provided within a "when" statment, the var is automatically passed as proc's argument ;)