开发者

<< operator in ruby

I am quite new to ruby,

I came across the following code in rails, but I don't know how the "<<" operator works and what it does in the below code

def <<( rate )
  r = Rating.new
  r.rate = rate
  r.rateable = proxy_owner
  ...
  ...
end
class << ActiveRecord::Base
  ...
  ...
end

Can anybody explain to me?

Edit: here is the code https://github.com/azabaj/acts_as_开发者_开发技巧rateable/blob/master/lib/acts_as_rateable.rb


def <<( rating ): In your example, this is used to add a rating to a rateable model. (E.g. in acts_as_rateable.rb:41), similar to appending something to a string (str << "abc"). As it is within a module, it will only be included for the models that you declare as rateable.

class << ClassName:

All the methods inside of this block will be static / class methods (see this blog entry). (In this case, all the models will have the methods Model.example_static_method.)


Nearly all operators in Ruby are actually instance methods called on the object preceding them.

There are many different uses for << depending on the object type you're calling it on. For example, in an array this works to push the given value onto the end of the array.

It looks like this is for a Rails model object, so in that case I would say that this is an auxiliary method called when you append a model object to model object collection. For example, in this case you might be appending a Rating to a Product.

If you showed the whole method definition and showed what class it's in, I could provide a more specific answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜