哈希数组,如何添加新元素?

时间:2018-04-17 14:39:21

标签: ruby-on-rails ruby

我有一个像这样的元素

customers =  [{ name: 'John Doe', age: 30, height: 175 }, { name: 'John Doe', age: 30, height: 175 } ... etc]

我知道这是一个简单的问题,但我怎样才能为这个元素添加另一个客户。即。

{name: 'Jane' , age: 25, height 150 } 

提前致谢!

1 个答案:

答案 0 :(得分:3)

使用shovel方法:

customers =  [{ name: 'John Doe', age: 30, height: 175 }, { name: 'John Doe', age: 30, height: 175 }]
new_customer = {name: 'Jane' , age: 25, height: 150 } 
customers << new_customer
 => [{:name=>"John Doe", :age=>30, :height=>175}, {:name=>"John Doe", :age=>30, :height=>175}, {:name=>"Jane", :age=>25, :height=>150}]