[#3986] Re: Principle of least effort -- another Ruby virtue. — Andrew Hunt <andy@...>

> Principle of Least Effort.

14 messages 2000/07/14

[#4043] What are you using Ruby for? — Dave Thomas <Dave@...>

16 messages 2000/07/16

[#4139] Facilitating Ruby self-propagation with the rig-it autopolymorph application. — Conrad Schneiker <schneik@...>

Hi,

11 messages 2000/07/20

[ruby-talk:03805] Re: Immature idea for case-when

From: Dave Thomas <Dave@...>
Date: 2000-07-04 17:13:05 UTC
List: ruby-talk #3805
Aleksi Niemel<aleksi.niemela@cinnober.com> writes:

> I got an idea for enhancing (?) case-when. Now 'when' actually forces the
> use of '==='. What if not?
> 
>   case {|ancestor| obj.ancestors.include? ancestor}
>   when Foo
>     puts "Hey we have a Foo descendant here."
>   when Bar
>     puts "Blaahr."
>   end

Well, you can do something (almost) equivalent in standard Ruby--you
can associate closures with the 'when' conditions:

    # This is the code behind the curtains

     class When
       def initialize(aCheck)
         @check = aCheck
       end
       def ===(thing)
         @check.call(thing)
       end

     end

     def check(&proc)
       When.new(proc)
     end


     # Let's try it in a simple case...

     [1, 3, 4, 6, 7, 8, 9 ].each do |number|

       case number

       when check {|n| n % 2 != 0 && n % 3 != 0 }
         puts "#{number} is prime < 10"

       when check {|n| n & 1 == 1}
         puts "#{number} is odd"

       when check {|n| n & 1 == 0}
         puts "#{number} is even"

       else
         puts "#{number} is unknown"
       end

     end



Regards


Dave

In This Thread

Prev Next