Project

General

Profile

Actions

Feature #17315

open

Hash #transform

Added by dsisnero (Dominic Sisneros) 10 months ago. Updated 10 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:100765]

Description

Add new methods to transform or transform! both the keys and the values of a hash.
#7793

h = {'name' => 'dominic ', 'email' => 'dominic.mail.com '}
h.transform!{|k,v| [k.to_sym, v.strip]}
h # => {name: 'dominic', email: 'dominic.mail.com'}

Updated by marcandre (Marc-Andre Lafortune) 10 months ago

  • Status changed from Open to Closed

You'll be happy to hear that this is exactly what to_h does already.

Updated by marcandre (Marc-Andre Lafortune) 10 months ago

  • Status changed from Closed to Open

I'll reopen this, as you are asking for a mutating version of to_h.

Actions #3

Updated by sawa (Tsuyoshi Sawada) 10 months ago

  • Description updated (diff)
Actions #4

Updated by sawa (Tsuyoshi Sawada) 10 months ago

  • Description updated (diff)

Updated by sawa (Tsuyoshi Sawada) 10 months ago

marcandre (Marc-Andre Lafortune) wrote in #note-2:

I'll reopen this, as you are asking for a mutating version of to_h.

It might be strange to have transform! as the destructive counterpart to to_h. Perhaps, the naming should be Hash#to_h!? Wait. That looks even more strange.

Updated by marcandre (Marc-Andre Lafortune) 10 months ago

I didn't suggest anything, as I don't see a good name, and I don't see the appeal of this method:

  • it can not be more efficient than update + to_h
  • there's not a frequent usecase that I know of
  • seems like avoidable mutation
  • to_h! would be strange (conversion + mutation...?)

Updated by dsisnero (Dominic Sisneros) 10 months ago

to_h works for me even though it is unintuitive a name for monadic mapping a hash. I wish we had a common name function name in Enumerable for monadic mapping that would return the same Class that we map over.

Actions

Also available in: Atom PDF