How do you overload the << operator in Ruby?
operator-overloading, operators, ruby, ruby-on-rails
Solution
You need to do that from within a class. Like this:
class Whatever
attr_accessor :roles
def initialize
@roles = []
end
end
You can't really have a `<<roles` method. You'd have to have an accessor for `roles` that supports the `<<` operator.
EDIT: I've updated the code. Now you can see how the `<<` operator should be overloaded, but you can also do what the `roles<<` part. Here's a small snippet of it's usage:
w = Whatever.new
w << "overload for object called"
# and overloads for the roles array
w.roles << "first role"
w.roles << "second role"
Problem
I'm not sure how to accomplish overloading the << operator for a method. This is how I assumed it would work: ``` def roles<<(roles) ... end ``` That however, throws errors. Any suggestions?