views:

1162

answers:

5

I'm sure this is simple but I can't seem to get it:

Works:

@build1 = Booking.build_booking('2009-06-13',3,2,18314)
@build2 = Booking.build_booking('2009-06-13',3,4,18317)
@build = @build1 + @build2

What I want to work...

#for item in @cart.items do
#  @build << Booking.build_booking('2009-06-13',3,2,18314)
#end

Doesn't work either...

#(1..3).each do |i|
#  @build << Booking.build_booking('2009-06-13',3,2,18314)
#end
+1  A: 

@build will need to be an array, or an object that responds to <<, for @build << to work.

When you've done:

@build = @build1 + @build2

What is the value of @build?

dylanfm
according to the console after the addition @build.class = Array as are @build1 and @build2
holden
+4  A: 

For the two iterating examples you'd need to set @build prior to calling << on it.

I'm not sure what build_booking is returning but if it's an array (I'm guessing from the first, working, example) then you'd probably want to add the result of build_booking to @build. E.g.

@build = []
for item in @cart.items do
  @build += Booking.build_booking('2009-06-13',3,2,18314)
end
Shadwell
ah perfect... i tried += as my first guess but forgot the Array.new!
holden
This is probably a good place to use inject too. http://www.ruby-doc.org/core/classes/Enumerable.html#M003171
dylanfm
I think the approach of Magnar is better than most here, since it generates the array by converting cart items into bookings directly instead of explicitly declaring an array and then making incremental alterations using the += operator.Array#map or the alternative name Array#collect is a very powerful tool.
tadman
@dylanfm #inject would certainly work, but it's overkill; #map works just fine!
James A. Rosen
A: 
@build = []
for item in @cart.items do
  @build += Booking.build_booking('2009-06-13',3,2,18314)
end


 @build.flatten!

flatten will will work even Booking.build_booking is returning an array of bookings

Subba Rao
+6  A: 

I prefer using the wonderful array-methods that ruby has to offer over a for loop:

@build = @cart.items.map { |item| Booking.build_booking('2009-06-13',3,2,18314) }
Magnar
A: 

The quick approach, though, would be to simply declare the array to combine the two elements:

@build = [ @build1, @build2 ]

I'd use an approach like Magnar, though, which is much more concise.

tadman