0

I have a hash {:a => b} and I want to add a value to that key and turn it into an array of values keeping the previous one.

So the result would be {:a => [b, c]}

Is there a better way to do this than iterating through the hash?

1
  • 1
    No :-) You have to iterate anyway, so what is your question? "What is the shortest way to reach ..."? Commented Feb 27, 2013 at 14:25

2 Answers 2

4

Try This.

h = {a: b}
h[:a] = ((a[:a].is_a? Array) ? a[:a] : [a[:a]]) << c
Sign up to request clarification or add additional context in comments.

1 Comment

The original question doesn't mention whether b might possibly already be an array. If that's possible, you may want add a check.
0

Simple solution would be to create a Hash of Arrays:

h = {}
h[:a] = []
h[:a].push(b)
h[:a].push(c)

What I mean: Even if there's only one value use an array. That makes handling easier.

Comments

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.