Feature #9635

Map a hash directly to a hash

Added by Andrey Mikhaylov over 1 year ago. Updated over 1 year ago.

[ruby-core:61462]
Status:Open
Priority:Normal
Assignee:-

Description

There should be a way to directly map a hash to a hash.

The current way to do it is not very graceful:

{foo: 'foo', bar: 'bar'}.map { |key, value| [key.upcase, value.reverse] }.to_h     # => { :FOO => 'oof', :BAR => 'rab' }

I think there should be a simpler and more natural way to do that. Something like this:

{foo: 'foo', bar: 'bar'}.hashy_map { |key, value| key.upcase => value.reverse }    # => { :FOO => 'oof', :BAR => 'rab' }

History

#1 Updated by Andrey Mikhaylov over 1 year ago

Ok, what i suggest is not a valid Ruby syntax. It should be

.hashy_map { |key, value| {key => value} }

which is hardly sweeter than

.map { |key, value| [key, value] }.to_h

and also goes against common practice of returning multiple results in an array.

@apeiros from irc://irc.freenode.net/ruby/ has cleared this out to me and suggested this very compact and efficient implementation: https://gist.github.com/apeiros/9527275

#2 Updated by Matthew Kerwin over 1 year ago

At the risk of being terse, https://bugs.ruby-lang.org/issues/7793

Also available in: Atom PDF