Project

General

Profile

Actions

Feature #11818

closed

`Hash#compact`

Added by sawa (Tsuyoshi Sawada) about 9 years ago. Updated about 8 years ago.

Status:
Closed
Target version:
-
[ruby-core:72133]

Description

I request Hash#compact and Hash#compact! that remove the key-value pairs whose value is nil, as follows:

h1 = {a:, 1, b: nil, c: 2}
h1.compact # => {a: 1, c: 2}
h1 # => {a: 1, b: nil, c: 2}

h2 = {a:, 1, b: nil, c: 2}
h2.compact! # => {a: 1, c: 2}
h2 # => {a: 1, c: 2}

h3 = {a:, 1, c: 2}
h3.compact! # => nil
h3 # => {a: 1, c: 2}

I believe people have frequent need to do this.

Updated by sawa (Tsuyoshi Sawada) about 9 years ago

Sorry, the code was invalid. It should be:

h1 = {a: 1, b: nil, c: 2}
h1.compact # => {a: 1, c: 2}
h1 # => {a: 1, b: nil, c: 2}

h2 = {a: 1, b: nil, c: 2}
h2.compact! # => {a: 1, c: 2}
h2 # => {a: 1, c: 2}

h3 = {a: 1, c: 2}
h3.compact! # => nil
h3 # => {a: 1, c: 2}

Updated by danielpclark (Daniel P. Clark) about 9 years ago

You can do this with Hash#delete_if

{a: 1, b: nil, c: 2}.delete_if {|k,v| v.nil?}
# => {:a=>1, :c=>2}

Updated by sikachu (Prem Sichanugrist) about 9 years ago

Active Support has this: http://api.rubyonrails.org/classes/Hash.html#method-i-compact

I'm +1 on porting this method. While I think it's possible using a block form and delete_if, this method has a good name and intention that could live by its own.

Updated by dwfait (Dwain Faithfull) almost 9 years ago

Prem Sichanugrist wrote:

Active Support has this: http://api.rubyonrails.org/classes/Hash.html#method-i-compact

I'm +1 on porting this method. While I think it's possible using a block form and delete_if, this method has a good name and intention that could live by its own.

https://github.com/ruby/ruby/pull/1184/files

In anticipation of this being approved, I have raised a PR of a sample implementation, along with some benchmarks against the Active Support implementation and tests.

This is my first time contributing to Ruby, so I apologise if I've jumped the gun or done anything wrong - seemed like a good issue to pick up for someone new to the codebase, with no possible breaking changes, and some good performance gains to be had.

Updated by mrkn (Kenta Murata) over 8 years ago

  • Status changed from Open to Assigned
  • Assignee set to matz (Yukihiro Matsumoto)

Updated by matz (Yukihiro Matsumoto) over 8 years ago

Accepted.

Matz.

Actions #7

Updated by nobu (Nobuyoshi Nakada) about 8 years ago

  • Status changed from Assigned to Closed

Applied in changeset r56414.


hash.c: add compact and compact! methods

  • hash.c (rb_hash_compact, rb_hash_compact_bang): Removes nil
    values from the original hash, to port Active Support behavior.
    [Feature #11818]
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0