[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Generic method without case/when?

Paatsch, Bernd

2/14/2006 2:19:00 AM

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
2 Answers

Tim Hunter

2/14/2006 2:36:00 AM

0

Paatsch, Bernd wrote:
> 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
>

Check the Object#send method:

obj.send('method', arg1, arg2...)

Robert Klemme

2/14/2006 9:34:00 AM

0

Paatsch, Bernd wrote:
> 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