Project

General

Profile

Actions

Feature #11818

closed

`Hash#compact`

Feature #11818: `Hash#compact`

Added by sawa (Tsuyoshi Sawada) over 10 years ago. Updated over 9 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) over 10 years ago Actions #1 [ruby-core:72134]

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) over 10 years ago Actions #2 [ruby-core:72145]

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) over 10 years ago Actions #3 [ruby-core:72147]

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) over 10 years ago Actions #4 [ruby-core:72694]

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) almost 10 years ago Actions #5 [ruby-core:76517]

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

Updated by matz (Yukihiro Matsumoto) over 9 years ago Actions #6 [ruby-core:76779]

Accepted.

Matz.

Updated by nobu (Nobuyoshi Nakada) over 9 years ago Actions #7

  • 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: PDF Atom