Newbie question: how to read the "<<"

I apologize about being a total beginner with Ruby and Rails. I’ve
worked much more with PHP. I’m trying to read this code:

def save_order
@cart = find_cart
@order = Order.new(params[:order])
@order.line_items << @cart.items
if @order.save
@cart.empty!
redirect_to_index(@order.process_transaction)
else
render(:action => ‘checkout’)
end
end

In the line

@order.line_items << @cart.items

what does the << mean?

Hi –

On Tue, 21 Nov 2006, Jake Barnes wrote:

 redirect_to_index(@order.process_transaction)

what does the << mean?
It looks like an operator, but is actually a method. What you’re
seeing is syntactic sugar for:

@order.line_items.<<(@cart.items)

For ActiveRecord collections, << adds a record to the collection,
taking care of database manipulation behind the scenes.

Do you have a Ruby language book? I can recommend one that covers all
the things you’ve been asking about, and is optimized to give the best
Ruby coverage for Rails developers :slight_smile:

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

puts “ab” << “c”
#yields “abc”

[“a”, “b”]

or with arrays:
irb(main):001:0> [“a”, “b”] << “c”
=> [“a”, “b”, “c”]

On Nov 22, 2006, at 01:41 , Jake Barnes wrote:

In the line

@order.line_items << @cart.items

what does the << mean?

It’s a method call, usually ‘append’ and usually described in the API
reference.

In your specific case, I would guess it’s a method on some
association, which means it’s documented in the Rails API:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/
ClassMethods.html#M000530


Jakob S. - http://mentalized.net

Do you have a Ruby language book? I can recommend one that covers all
the things you’ve been asking about, and is optimized to give the best
Ruby coverage for Rails developers :slight_smile:

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

I’d recommend the same book. It’s a great read.

Bill