1

There is a hash {'results' => [], 'snow' => [], 'ham' => [], 'plow' => [] }

and I want to build a string dynamically (the keys may change), which has all the keys, excluding "results", which looks like this "snow + ham + plow"

How do i do this?

1
  • yeah you're right, i was using python syntax, i'll edit the post and fix it Commented Mar 27, 2014 at 3:06

2 Answers 2

3

Use Hash#keys to get the keys, Array#reject to reject the "results" one, and Array#join to join them into a String:

hash.keys.reject { |k| k == "results" }.join(" + ")
Sign up to request clarification or add additional context in comments.

Comments

3

Two other ways (#1 being my preference):

h = {'results' => [], 'snow' => [], 'ham' => [], 'plow' => [] }

#1

(h.keys - ['results']).join(' + ') #=> "snow + ham + plow"

#2

a = h.keys
a.delete('results')
a.join(' + ') #=> "snow + ham + plow" 

2 Comments

Well, without explicit enumeration. Array#delete and Array.join both have to iterate behind the scenes.
Good point, @Chuck. No denying that. (Applies to keys as well.) Edited. Readers: formerly I said "Without iterating:".

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.