conditional chaining in ruby

后端 未结 9 2178
一生所求
一生所求 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 21:02

    If you're using Rails, you can use #try. Instead of

    foo ? (foo.bar ? foo.bar.baz : nil) : nil
    

    write:

    foo.try(:bar).try(:baz)
    

    or, with arguments:

    foo.try(:bar, arg: 3).try(:baz)
    

    Not defined in vanilla ruby, but it isn't a lot of code.

    What I wouldn't give for CoffeeScript's ?. operator.

提交回复
热议问题