3

I have a hash which, I have 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...

1 Answer 1

6

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] }
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way that I can order the hash so that lets say the highest price array is first ... while keeping the integrity Cheers for the help btw
No, in Ruby hashes are unordered, so you cannot "sort" them as such (though this may change in Ruby 1.9). You would need to use a library that extends Hash, like Ruby Facets' Dictionary class: github.com/trans/facets/blob/master/lib/more/facets/…
Is it possible to to do hsh["Apple"] << [9999, 8888], so that you get { "Apple" => [1, 5.99, 9999, 8888], "Banana" => [5, 9.99] }, but without using a loop?
@user2340939 Use Array#concat: hsh["Apple"].concat([9999, 8888]) or Array#push: hsh["Apple"].push(9999, 8888).
@Jordan I've figured out the first case, but the second one seems handy also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.