-1

I'm trying to add an alias to a class method that uses an operator in ruby. My problem is that i would like to keep the new alias with the sintax of the operator

def &(estrategia) does something end

I would like to have the same result doing Myclass.new & estrategia, but like this: Myclass.new with estrategia Is there a way in ruby, to achieve this?

   class Trait
     def & (strategy)
        p "hi #{strategy}"
     end
   alias with &
  end

 Trait.new & "John"
 Trait.new with "John"
facuhump
  • 13
  • 1
  • 3

3 Answers3

0

You probably miss .with your method call.

class Trait
     def & (strategy)
        p "hi #{strategy}"
     end
   alias with &
end

Trait.new.& "John"
Trait.new.with "John"
Masafumi Okura
  • 694
  • 3
  • 12
0

Ruby has particular operators you can override, like %, +, and &, but you can't just invent arbitrary operators on a whim. You need to work with pre-existing ones.

This is a function of how the Ruby parser works. It can only identify a pre-defined set of symbols outside of regular method calls.

Trait.new.with x is a method call, equivalent to Trait.new.send(:with, x), while Trait.new with x is Trait.new(with(x)) which is not what you want.

Your alias creates a method, it does not create an operator. You cannot create a brand-new operator.

You're going to have to decide between the two forms x & y vs. x.with y.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

The & is a default operator in Ruby and you can override with your method. But with is not an operator. In this case, you will need to add a new operator to Ruby, which is kind of tricky. There is a discussion about adding new operator in Ruby here Define custom Ruby operator but I don't think it's worth to do that.

Huy Ha
  • 179
  • 4