Search code examples
ruby-on-railsruby

Ruby: How can I return a logical operator like && or ||


I am building a rules engine and I would like to dynamically update my logical operators. Because of this I'd like to return the && or || from a method. But I'm having a heck of a time doing this. How can I?

This is a basic example of what I'm trying to do:

module Rules::Engine
  module_function

  def call
    a = true
    b = false
    ap "what does this return #{a logic b}"
  end

  def logic(a)
    if a
      return &&
    else
      return ||
    end
  end

end

Solution

  • Try this:

    module Rules::Engine
      module_function
      def call
        a = true
        b = false
        operator = logic(a)
    
        puts a.send(operator, b)
      end
    
      def logic(and_operator)
        and_operator ? :& : :|
      end
    end

    You can also use eval, instead of send, but it's not recommended by rubocop