Generic method without case/when?

Discussion in 'Ruby' started by Paatsch, Bernd, Feb 14, 2006.

  1. ------_=_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--
    Paatsch, Bernd, Feb 14, 2006
    #1
    1. Advertising

  2. 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
    Robert Klemme, Feb 14, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Thorsten Bunte

    Generic in CASE choice ?!?

    Thorsten Bunte, Apr 28, 2005, in forum: VHDL
    Replies:
    4
    Views:
    706
    Taras_96
    Apr 29, 2005
  2. Murat Tasan
    Replies:
    1
    Views:
    8,037
    Chaitanya
    Feb 3, 2009
  3. MariuszK

    case and generic

    MariuszK, Jul 11, 2006, in forum: VHDL
    Replies:
    5
    Views:
    456
  4. Replies:
    2
    Views:
    433
  5. minlearn
    Replies:
    2
    Views:
    453
    red floyd
    Mar 13, 2009
Loading...

Share This Page