Legacy code and aliases to user input

M

Marc Heiler

I have a rather old code with a very long case/menu, which
acts on user-supplied input. I already fear that I will have
to rewrite it heavily, but before I start I thought I go and
ask here.

A typical line of that case/menu looks like so:


when "foobar","foo","f"
do_something()

Obviously, I did want the user be able to type foobar, foo, or f
and have the same method or code invoked. Lateron I realized that
this was not optimal, one better approach would have been this:

alias_listing:
foo, f -> pointing to foobar, which then invokes do_something()

(The real scenario is a bit more complicated, but the code above
serves as a good trivial example.)

How to solve the above? Using a big hash which keeps all
aliases and only leave a single entry per when line, like so?

# process input here and check on aliases, and then replace
# them pointing to "foobar"?
when "foobar"
do_something
when "blafoo"
do_something_else
 
J

Joel VanderWerf

Marc said:
How to solve the above? Using a big hash which keeps all
aliases and only leave a single entry per when line, like so?

Hashing is fine. Some alternatives:

Regex:

when /^f(oo(bar)?)?$/

Splat:

FOOBAR = %w{ f foo foobar }

...

when *FOOBAR
 

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,773
Messages
2,569,594
Members
45,114
Latest member
GlucoPremiumReview
Top