Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to array in Ruby

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
like image 871
holden Avatar asked Jun 11 '09 11:06

holden


People also ask

How do you add an array to an array in Ruby?

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

How do you add an element to an array array?

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().


1 Answers

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) }
like image 164
Magnar Avatar answered Oct 16 '22 19:10

Magnar