14

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

5 Answers 5

27

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) }
Sign up to request clarification or add additional context in comments.

Comments

16

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

4 Comments

ah perfect... i tried += as my first guess but forgot the Array.new!
This is probably a good place to use inject too. ruby-doc.org/core/classes/Enumerable.html#M003171
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.
@dylanfm #inject would certainly work, but it's overkill; #map works just fine!
0

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

1 Comment

according to the console after the addition @build.class = Array as are @build1 and @build2
0

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.