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?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.