Interesting, even if not recommended, it’s nice to know it’s possible. Thanks for sharing.
Yes, you’re right. Technically you just define a setter with the = postfix. So, yeah, you’re not technically overriding an operator. I should have been more
specific. In my case, I mostly used it to override Array setters, like so:
class MyCustomArr < Array
def []=(key, value)
#Do something magic…
puts “#{key} = #{value}”
end
# ...
end
Ruby then adds some syntactic sugar to allow you to call this method like so:
irb(main):006:0> MyCustomArr.new['foo'] = ‘bar'
foo = bar
In the case of setters, you’d just use attr_accessor (or attr_writer to create just the setter), most often. To manually create it:
class Bar
def foo=(barz)
puts bar
end
end
And you can call it like:
irb(main):006:0> Bar.new.foo = ‘Hello World'
Hello World
—
Maybe it would make more sense to create a macro that would allow you to call methods (maybe marked with some metadata) with this syntactic sugar instead of overriding all `=` instances? I’m not 100% what’s the OP use case, though.
Cheers,
— Marcelo