Phrogz
11/24/2007 3:01:00 PM
On Nov 24, 4:23 am, Marc Heiler <sheve...@linuxmail.org> wrote:
> user_input = $stdin.gets.chomp
>
> case user_input
> when 'x'
> puts 'this is a test'
> end
>
> # So far so fine. Now I want to add something like
>
> when 'y'
> puts 'yay, a new test'
> end
>
> What would be the simplest or most elegant way?
> A hash with key -> action ?
The simplest, most elegant way, would be to just type it into the same
case code :)
If you want to be able to define the (arbitrary) results of a
comparison separate from the comparison itself, I think you need to
use blocks/procs. A Hash would certainly be a good way to store this,
assuming a simple case-like #=== comparison is all you need.
However, the syntax of defining a Hash of procs may not be the most
ideal, depending on your scenario. I might use a method wrapper like
so:
class ConditionMapper
def initialize
@conditions = {}
end
def when( *conditions, &action )
conditions.each{ |condition| @conditions[ condition ] = action }
end
def check( obj )
@conditions.each{ |condition,action|
if condition === obj
return action[ obj ]
end
}
end
end
english_match = ConditionMapper.new
english_match.when( 1..5 ){ |x|
puts "#{x} is between one and five"
}
english_match.when( 7, 42 ){ |x|
puts "#{x} is a cool number"
}
english_match.check( 4 )
#=> 4 is between one and five
english_match.check( 42 )
#=> 42 is a cool number
> Only problem is that the action could be invoking a method or creating
> an object etc... and i dont want to use proc or lambda's at all.
Why not?