How to add to array in Ruby

32,327

Solution 1

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

Solution 2

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) }
Share:
32,327
holden
Author by

holden

Updated on August 02, 2022

Comments

  • holden
    holden over 1 year

    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
    
  • holden
    holden almost 15 years
    according to the console after the addition @build.class = Array as are @build1 and @build2
  • holden
    holden almost 15 years
    ah perfect... i tried += as my first guess but forgot the Array.new!
  • dylanfm
    dylanfm almost 15 years
    This is probably a good place to use inject too. ruby-doc.org/core/classes/Enumerable.html#M003171
  • tadman
    tadman almost 15 years
    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.
  • James A. Rosen
    James A. Rosen almost 15 years
    @dylanfm #inject would certainly work, but it's overkill; #map works just fine!