13

I am a newbie in Ruby on Rails. In a Rails application, I saw some code like following:

In model, there is a class Car:

class Car < ActiveRecord::Base
  ...
end

In controller, there is a method "some_method"

class CarsController < ApplicationController

   def some_method
      @my_car = Car.new()

      #What does the following code do? 
      #What does "<<" mean here?
      @my_car.components << Component.new()
   end


end

I got three questions to ask:

1. In the code in controller @my_car.components << Component.new() , what does it do? What << means ?

2. Are there any other usages of "<<" in Ruby-On-Rails or in Ruby ?

3. Does Car class must explicitly define the has_many association with Component class if "<<" is used Or is the "<<" can be used to add a new association to Car, even the association is not defined in Car class explicitly?

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
Mellon
  • 37,586
  • 78
  • 186
  • 264
  • You can use << also with a string. `"something " << "other"` results in `"something other". You can overload the << operator in any class, just like in C++. Also, note that it's just one `<` in the model, and it signify inheritance. – CamelCamelCamel Oct 26 '11 at 07:26

3 Answers3

23

After your edit:

Point 1

@my_car.components << Component.new()

is the same as

@my_car.components.push(Component.new())

Point 2

It lets you add items to a collection or even concatenate strings.

Some links:

notice you can naturally overload or define your own.

Point 3

Relationships must be explicit, otherwise Rails can't create the adequate methods: @my_car.components wouldn't have any sense.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • 2
    Does it also hint that the Car object is associated with Component object with "has_many" association (Car has_many Component)? – Mellon Oct 26 '11 at 07:24
  • @ apneadiving , sorry for the late acceptance, your answer is excellent! Thank you. – Mellon Oct 26 '11 at 08:03
1

Concerning 1. & 2., I summarized the different meanings of << here.

Community
  • 1
  • 1
emboss
  • 38,880
  • 7
  • 101
  • 108
0

<< adds an item to an array.

So in the example above you are adding a new component to the Car.components array. It's part of Ruby and you'll see it used often.

nheinrich
  • 1,841
  • 11
  • 17