search

Home  >  Q&A  >  body text

lambda - Ruby中如何避免使用case...when

例如,我有如下代码:

case opt
when "opt1"
  method1(param1, param2)
when "opt2"
  method2(param1, param2, param3)
end

请教有没有好方法避免使用case...when,这里每个when里面调用的处理方法传的参数也是不一样的。动态方法调用?用block是否可行?
用动态方法调用,方法名和参数列表提前配置在一个hash中可以达到要求。不知道用block/lambda/proc之类的能否做到?

天蓬老师天蓬老师2780 days ago910

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-04-22 08:58:14

    It’s ok.
    For details, you can read the book Ruby Metaprogramming. It will tell you how to abstract it.

        method_name = "#{params[:type]}_report"
        @orders = Order.done.send(method_name,params[:month],params[:year]) rescue     Order.done.send("daily_report")
    

    Here I have defined three scopes daily_report monthly_report weekly_report
    The above code dynamically generates the names of three functions and then passes parameters to them.

    a.send(method_name,arg1,arg2,...)
    

    Many parameters can be given here. The first parameter is the method name, and the following parameters are all parameters required by the method.
    Then you can generate specific functions based on opt, if the functions are the same thing. Just use optional parameters for parameters.
    Ruby accepts any number of parameters. You must add a * sign before a parameter. In the code of the method, this parameter is represented as an array, which contains 0 or more parameters passed to this position.

    def haha(a *b)
      puts a
    end
    

    reply
    0
  • Cancelreply