Add Hash#map_values to ActiveSupport to simplify a common pattern#15819
Add Hash#map_values to ActiveSupport to simplify a common pattern#15819guilleiguaran merged 1 commit intorails:masterfrom
Hash#map_values to ActiveSupport to simplify a common pattern#15819Conversation
|
@chancancode I remember you wanted to add this some time ago. @jeremy I'm not good with names WDYT? |
|
Hash has method |
|
Urgh! This make me think this method should be private API for Rails. I really don't want to have a |
Perhaps we can...
|
|
I am 👍 on backporting |
|
What do you think about renaming |
|
Is the behavior of |
|
No, it is not. See the API docs for |
|
That's what I thought, hence 👎 on having |
|
I'm fine with that.
|
|
Strong 👎 on renaming an existing ActiveSupport method just because its precedent doesn't match your new method's proposed name 😐 I think avoiding "map" would be a better move anyway:
|
|
I'm fine with
|
|
Updated. |
There was a problem hiding this comment.
transform_keys and friends live in /core_ext/hash/keys.rb. To be consistent, this file could be called /core_ext/hash/values.rb.
|
Submitted upstream as well if anyone would like to comment there. https://bugs.ruby-lang.org/issues/9970 |
|
@sgrif can you rebase this? |
|
Done On Sat, Jun 28, 2014 at 8:14 AM, Guillermo Iguaran <notifications@github.com
Thanks, |
Didn't get a chance to convert existing code, I'll skim through the code base to make use of this later this afternoon.
|
Any more feedback on this? Writing a lot of methods in AR right now that could certainly make good use of this. |
Add `Hash#map_values` to ActiveSupport to simplify a common pattern
There was a problem hiding this comment.
In case it helps, maybe refactor the code as follows?:
def transform_values(&block)
each_with_object(self.class.new) do |(key, value), result|
result[key] = yield value
end
end
This would eliminate the need for an instance variable.
There was a problem hiding this comment.
It's a local variable, not an instance variable. And that spelling would severely curtail the advantage of this method: it currently avoids doing an allocation per hash entry.
Keys remain the same, but the values change.
Didn't get a chance to convert existing code, I'll skim through the code base to make use of this later this afternoon.