Forum: Ruby Generic method without case/when?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fd870ca69f1243766bd8697ea3415df2?d=identicon&s=25 Paatsch, Bernd (Guest)
on 2006-02-14 03:19
(Received via mailing list)
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
37a3c73ffbf864e4b28f7f2384ee12ce?d=identicon&s=25 Timothy Hunter (tim-hunter)
on 2006-02-14 03:38
(Received via mailing list)
Paatsch, Bernd wrote:
> 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...)
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2006-02-14 10:38
(Received via mailing list)
Paatsch, Bernd wrote:
> 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
This topic is locked and can not be replied to.