conditional chaining in ruby

后端 未结 9 2171
一生所求
一生所求 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:51

    I ended up writing the following:

    class Object
    
      # A naïve Either implementation.
      # Allows for chainable conditions.
      # (a -> Bool), Symbol, Symbol, ...Any -> Any
      def either(pred, left, right, *args)
    
        cond = case pred
               when Symbol
                 self.send(pred)
               when Proc
                 pred.call
               else
                 pred
               end
    
        if cond
          self.send right, *args
        else
          self.send left
        end
      end
    
      # The up-coming identity method...
      def itself
        self
      end
    end
    
    
    a = []
    # => []
    a.either(:empty?, :itself, :push, 1)
    # => [1]
    a.either(:empty?, :itself, :push, 1)
    # => [1]
    a.either(true, :itself, :push, 2)
    # => [1, 2]
    

提交回复
热议问题