tags:

views:

42

answers:

2

Does anyone know in which class/module the = method is in Ruby?

I want to convert

a = b

into

a equals b

So I have to know in which class/module it is so I can make an alias.

Thanks.

+4  A: 

The = is the assignment operator. It can not be redefined.

Moreover, you can not define new operators. As Jörg points out, a equals b is the same as a(equals(b)) or equivalently self.a(self.equals(b)), so, you'd need an object that responds to both the :a message and the :equals message.

Marc-André Lafortune
is there a way to make "a equals b" as a syntatic sugar? (just for learning purpose, even if its not best practice)
never_had_a_name
`a equals b` is the same as `a(equals(b))` which is the same as `self.a(self.equals(b))`. So, you'd need an object that responds to both the `:a` message and the `:equals` message and you need to evaluate your DSL in the context of that object.
Jörg W Mittag
@Jörg: oh, right...
Marc-André Lafortune
But you don't mean "equals"! You mean "assignment"!
Justice
A: 

I was trying to provide an answer, but it looks like Ruby is smarter than I am:

# Adults! Don't try this at work. We're what you call "amateurs"
def a=(*args)
  if args.size == 1
    STDERR.puts "Assignment"
    @a = args[0]
  else
    STDERR.puts "Comparison"
    return args[0] == args[1]
  end
end

self.a=([1,2,3])
Assignment
=> [1, 2, 3]

self.a=([1,2,3],[4,5,6])
SyntaxError: (irb):12: syntax error, unexpected ',', expecting ')'
self.a=([1,2,3],[4,5,6])
            ^
        from C:/Ruby19/bin/irb:12:in `<main>'
self.send(:a=, [1,2,3],[4,5,6])
Comparison
=> false
Andrew Grimm