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 --

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?

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

puts "ab" << "c" #yields "abc"

["a", "b"]

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

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: