Topic: Equivalent to .= (dot equals) in Ruby?

I'm having a hard time wrapping my mind around these iterators in Ruby.  I'm sure there is a simple slick way to do this, but I can't seem to track down the Ruby equivalent of the .= (dot equal) from PHP

I am simply trying to build a variable that is a string listing all of the items and their corresponding quantities in my shopping cart.  The end result would be something like "Notebook x 3, Pencil x 2, Paper x 10"

In PHP I would just do something like the following...

foreach($items AS $item){
  $complete_string .= $item['title'].' x '.$item['quantity'];
}
return $complete_string

However, this does not seem to work in Ruby.  I can print this out on the page at any time with a for loop, but I need it in a variable to supply to the description portion of a payment processor
 
@cart.items.each do |item|
  @items.= item.title + " x " + item.quantity.to_s + ", "
end

Any thoughts?
Thanks.

Last edited by bilson (2007-05-22 14:11:45)

Re: Equivalent to .= (dot equals) in Ruby?

The direct equivalent in Ruby would be +=, but you can also use <<, so your example code would become:

foreach($items AS $item){
  $complete_string << $item['title'].' x '.$item['quantity'];
}
return $complete_string

Note that the 'append' operator (<<) also works for adding an item at the end of an array.

Re: Equivalent to .= (dot equals) in Ruby?

Yes, I had tried both of those but they do not seem to be working.

Here is the code...

@cart.items.each do |item|
  @items += item.title + " x " + item.quantity.to_s + ", "
end

If I remove the plus sign in front of the equals it prints the single item fine.  However, appending the += or << yields the following error...

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+

Thank you.

Last edited by bilson (2007-05-22 14:10:57)

Re: Equivalent to .= (dot equals) in Ruby?

It's because @items isn't defined so it doesn't know how to append a string to something undefined (nil). You need to set it to an empty string first:

@items = ''
@cart.items.each do |item|
  @items += item.title + " x " + item.quantity.to_s + ", "
end

Railscasts - Free Ruby on Rails Screencasts

Re: Equivalent to .= (dot equals) in Ruby?

Ahh...(feeling stupid)
Thanks Ryan.