Project

General

Profile

Actions

Feature #20738

open

Removing a specific entry from a hash literal

Added by ursm (Keita Urashima) about 2 months ago. Updated 27 days ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:119168]

Description

Sometimes I want to decide whether or not to add a particular entry to a hash depending on a condition. If the entire hash does not use nil, I can use Hash#compact.

{
  foo: 1,
  bar: bar? ? 2 : nil
}.compact

But if I want to remove only a specific entry while leaving the other nil, it is somewhat cumbersome. I have to either assign the hash once and change it destructively, or use Hash#reject.

h = {
  foo: 1,
  baz: nil
}

h[:bar] = 2 if bar?
{
  foo: 1,
  bar: bar? ? 2 : :drop,
  baz: nil
}.reject {|_, v| v == :drop }

As a suggestion, how about a special value that indicates an invalid key for the hash? With this, the above example could be written like this:

{
  foo: 1,
  bar: bar? ? 2 : Hash::DROP,
  baz: nil
} #=> {foo: 1, baz: nil}
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0