[英]Ruby - how to add an array to a hash key?
I have this loop: 我有这个循环:
car_data = Hash.new
Car.all.each do |c|
car_data[c.brand] = c.id
car_data['NEW'] << c.id if c.new == 1
end
I have this snipper and trying to save all the new cars to car_data['NEW']
, but this code keeps only one item in the hash (there should be 8). 我有这个侦听器,试图将所有新车保存到
car_data['NEW']
,但是此代码仅在哈希中保留一项(应该为8)。
I also tried to define that car_data['NEW']
as an array: 我还尝试将
car_data['NEW']
定义为数组:
car_data = Hash.new
car_data['NEW'] = Hash.new
Car.all.each do |c|
car_data[c.brand] = c.id
car_data['NEW'] << c.id if c.new == 1
end
But the result was the same - just one item. 但是结果是一样的-仅一项。 How do I save the whole array to the hash key element?
如何将整个数组保存到哈希键元素?
Thank you. 谢谢。
You wrote, that you tried to define (initialize) car_data['NEW']
as an array, but what you did is... initialized it as a hash. 您写道,您试图将
car_data['NEW']
定义(初始化)为数组,但是您所做的是...将其初始化为哈希。
Change: 更改:
car_data['NEW'] = Hash.new
To: 至:
car_data['NEW'] = []
The full code would look like: 完整的代码如下所示:
car_data = Hash.new
car_data['NEW'] = []
Car.all.each do |c|
car_data[c.brand] = c.id
car_data['NEW'] << c.id if c.new == 1
end
car_data['NEW']
has to be declared as Array
. car_data['NEW']
必须声明为Array
。
car_data = Hash.new
car_data['NEW'] = []
Car.all.each do |c|
car_data[c.brand] = c.id
car_data['NEW'] << c.id if c.new == 1
end
You can also do it in a single step 您也可以一步一步完成
car_data = { new: [] }
Car.all.each do |c|
car_data[c.brand] = c.id
car_data[:new] << c.id if c.new == 1
end
Frankly, it seems a little bit odd to me to use a Hash in that way. 坦白说,以这种方式使用Hash对我来说似乎有些奇怪。 In particular, mixin different kind of information in Hash is a very bad approach inherited from other non object oriented languages.
特别是,在Hash中混合不同种类的信息是从其他非面向对象的语言继承的非常糟糕的方法。
I'd use at least two separate variables. 我至少要使用两个单独的变量。 But I don't know enough about the context to provide a meaningful example.
但是我对上下文了解不足,无法提供有意义的示例。
car_data = Car.all.each_with_object(Hash.new { |h, k| h[k] = [] }) do |c, memo|
memo[c.brand] = c.id
memo['NEW'] << c.id if c.new == 1
end
or, simpler, let's create it on the fly if needed: 或者,更简单地说,让我们根据需要即时创建它:
car_data = Car.all.each_with_object({}) do |c, memo|
memo[c.brand] = c.id
(memo['NEW'] ||= []) << c.id if c.new == 1
end
Please also refer to comment by @tadman below, if the NEW
key is to be existing in any case. 如果在任何情况下都存在
NEW
密钥,也请参考下面@tadman的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.