开发者

push new element into array within hash

开发者 https://www.devze.com 2022-12-16 06:08 出处:网络
I have a hash which, I hav开发者_StackOverflow中文版e keys that uniquely identify each element within the hash.And within each element, I have an array.So my question is, how do I put another element

I have a hash which, I hav开发者_StackOverflow中文版e keys that uniquely identify each element within the hash. And within each element, I have an array. So my question is, how do I put another element inside that array within the hash.

{"Apple"=>[1, 5.99], "Banana"=>[5, 9.99]}

I'm looping through a result set, and I'm a little bit lost how to add another element to the array...


If your hash is called, for example, hsh, then the "Apple" array can be accessed by hsh["Apple"]. You can use this like any variable, so to add a value to that array just do hsh["Apple"] << some_value. Like so:

irb> hsh = { "Apple" => [1, 5.99], "Banana" => [5, 9.99] }
irb> hsh["Apple"] << 9999
=> { "Apple" => [1, 5.99, 9999], "Banana" => [5, 9.99] }
0

精彩评论

暂无评论...
验证码 换一张
取 消