conditional chaining in ruby

后端 未结 9 2165
一生所求
一生所求 2020-12-13 20:30

Is there a good way to chain methods conditionally in Ruby?

What I want to do functionally is

if a && b && c
 my_object.some_method_b         


        
9条回答
  •  粉色の甜心
    2020-12-13 20:50

    You could put your methods into an arry and then execute everything in this array

    l= []
    l << :method_a if a
    l << :method_b if b
    l << :method_c if c
    
    l.inject(object) { |obj, method| obj.send(method) }
    

    Object#send executes the method with the given name. Enumerable#inject iterates over the array, while giving the block the last returned value and the current array item.

    If you want your method to take arguments you could also do it this way

    l= []
    l << [:method_a, arg_a1, arg_a2] if a
    l << [:method_b, arg_b1] if b
    l << [:method_c, arg_c1, arg_c2, arg_c3] if c
    
    l.inject(object) { |obj, method_and_args| obj.send(*method_and_args) }
    

提交回复
热议问题