Hash#only adds nil values for keys
Reported by Brian Mitchell | June 6th, 2008 @ 05:20 PM
When using only on a hash with a missing key it will add all keys regardless of the current existence of each passable key.
{}.only(:foo) #=> {:foo => nil}
Comments and changes to this ticket
-

Brian Mitchell June 6th, 2008 @ 05:21 PM
- → Title changed from Hash#only adds nil keys to Hash#only adds nil values for keys
-
Michael Klishin (antares) June 7th, 2008 @ 12:57 AM
I think if you use only on Hash, you know what keys are in that hash. Not sure what behavior would be more intuitive.
-

Brian Mitchell June 7th, 2008 @ 02:23 AM
The specific case is where you want to filter not extract. So consider a case where I have some options which may or may not be set on some hash that I want to pass on to another function.
def f1(opts = {}) f2(opts.only(:key1, :key1)) endIn this case, if makes sense to avoid nil values which may or may not mean something depending on f2. For example, a common case where behavior might change is Hash#has_key?.
The behavior I would expect is as follows:
{}.only(:key) #=> {} {:key => nil}.only(:key) #=> {:key => nil} {:key => 42}.only(:key) #=> {:key => 42} -

Brian Mitchell June 7th, 2008 @ 02:29 AM
I just checked another implementation of this function in Rails (aka Hash#slice like Array#slice). They return similar results to my last comment.
-

Brian Mitchell June 7th, 2008 @ 02:56 AM
I've made a really simple implementation with tests over on github at: http://github.com/binary42/merb-...
Commit: 962a75fda82f3ecbfa8ca85cf9843fe8f9d55786
-

Brian Mitchell June 10th, 2008 @ 06:54 PM
- no changes were found...
-
Michael D. Ivey (ivey) June 12th, 2008 @ 12:39 AM
- → Assigned user changed from to Michael D. Ivey (ivey)
- → State changed from new to resolved
Applied in 33a25d088ddf4f6931a509f8dee712d48bb045cd
I hope no one was relying on the (broken) previous behavior
Please Login or create a free account to add a new comment.
You can update this ticket by sending an email to from your email client. (help)
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
