Scott Comboni wrote:
Paul L. wrote:
/ …
Also, look at case … when … then sample code online for the correct
syntax to use.
Thanks so much Paul for the quick response… I have about 100 codes to
search
Oh, that’s something different! In such a case, you should consider
writing
something called a “dispatcher” for the sake of efficiency and
maintainability.
This is an example where stating the problem fully at the outset can
really
help in finding a solution. At the level of 100 comparisons, you really
don’t want to use “if … else” or “case …when” either. There are
simply
too many comparisons for efficient use of either of the discussed
alternatives.
Here is an example dispatcher, with just a few defined command
resolutions,
just to show you the pattern:
#!/usr/bin/ruby -w
class Dispatcher
def initialize()
@dispatch_hash = {
“a” => :first_case,
“b” => :second_case,
“c” => :third_case
}
end
def first_case()
puts “first”
end
def second_case()
puts “second”
end
def third_case()
puts “third”
end
def default()
puts “unrecognized”
end
def dispatch(*s)
s.each do |com|
send(@dispatch_hash[com] || :default)
end
end
end
disp = Dispatcher.new
disp.dispatch(“a”,“b”,“c”,“d”)
Output:
first
second
third
unrecognized
The idea of this design is to maximize the speed and efficiency of
dispatching entered commands, without having to write a long,
inefficient
series of “if … else” or “case … when” structures. It is useful when
the number of commands becomes too large to handle efficiently any other
way.
This dispatcher will connect your entered string to its associated
command
very quickly, and it is easy to write and maintain. It is much easier to
understand and add to than the alternatives we discussed earlier.