Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you overload the << operator in Ruby?

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?

like image 953
Matthew Avatar asked Jul 27 '26 16:07

Matthew


1 Answers

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"
like image 68
Geo Avatar answered Jul 30 '26 08:07

Geo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!