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
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With