如何在Ruby中添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/980675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:20:43  来源:igfitidea点击:

How to add to array in Ruby

ruby-on-railsrubyarrayshash

提问by holden

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

回答by Magnar

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

我更喜欢使用 ruby​​ 在 for 循环中提供的美妙的数组方法:

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

回答by Shadwell

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

对于两个迭代示例,您需要@build在调用<<它之前进行设置。

I'm not sure what build_bookingis 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_bookingto @build. E.g.

我不确定build_booking返回的是什么,但如果它是一个数组(我从第一个,工作,示例中猜测)那么您可能想要将结果添加build_booking@build. 例如

@build = []
for item in @cart.items do
  @build += Booking.build_booking('2009-06-13',3,2,18314)
end

回答by dylanfm

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

@build将需要的阵列,或一个对象,该响应<<,对@build <<工作。

When you've done:

完成后:

@build = @build1 + @build2

What is the value of @build?

的价值是@build什么?

回答by Subba Rao

@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

即使 Booking.build_booking 返回一系列预订,flatten 也会起作用

回答by tadman

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.

不过,我会使用像 Magnar 这样的方法,它更简洁。