Generic method without case/when?

P

Paatsch, Bernd

------_=_NextPart_001_01C6310C.FA33C48B
Content-Type: text/plain

I like to write a generic method that calls different functions depending on
what string I parse to the method (see example) without having to use a
case-when? Is there a way to do that?

Process_easy("aFile", "Summer")

def process_easy(file, what)

if file.include?("#{what}#{NL}") then
constructor = CategoriesFactory.start_what # this is wrong. I like to
substitute and have: constructor = CategoriesFactory.start_summer
start = file.index("Summer#{NL}")
return constructor
# etc
end

-Bernd

------_=_NextPart_001_01C6310C.FA33C48B--
 
R

Robert Klemme

I like to write a generic method that calls different functions
depending on what string I parse to the method (see example) without
having to use a case-when? Is there a way to do that?

Process_easy("aFile", "Summer")

def process_easy(file, what)

if file.include?("#{what}#{NL}") then
constructor = CategoriesFactory.start_what # this is wrong. I
like to substitute and have: constructor =
CategoriesFactory.start_summer start = file.index("Summer#{NL}")
return constructor
# etc
end


Difficult to tell from this example. You could use send as Tim suggested.
But you might as well use a different approach:

- extract a class name from the string
- extract another string from the string and map that via a Hash to a
lambda / class whatever

MAP = {
"what" => lambda {|x| puts "doing what #{x}"},
"Summer" => lambda {|x| puts "it's summer"},
}
def process_easy(file)
cmd = MAP[file[/\w+$/m]] and cmd[file]
end

Kind regards

robert
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top