How do you overload the << operator in Ruby?

I am not sure how to overload the <<operator for the method. So I assumed this would work:

def roles<<(roles)
  ...  
end

This, however, causes errors. Any suggestions?

+3
source share
1 answer

You need to do this from class. Like this:

class Whatever
  attr_accessor :roles
  def initialize
    @roles = []
  end
end

You cannot have a method <<roles. For roleswhich the operator supports <<, you must have an accessor.

EDIT: I updated the code. Now you can see how the operator should be overloaded <<, but you can also do something in part roles<<. Here is a small snippet of this use:

w = Whatever.new
w << "overload for object called"
# and overloads for the roles array
w.roles << "first role"
w.roles << "second role"
+9

Source: https://habr.com/ru/post/1724192/


All Articles