Extending to an existing case menu

M

Marc Heiler

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 ?

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.

I would just like to "extend" the case menu somehow
(I need to split a huge case menu into "core" modules, and
stuff which a user wants to add to it)
 
P

Phrogz

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top