Feature #11818
closed`Hash#compact`
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
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
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
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
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
- Status changed from Open to Assigned
- Assignee set to matz (Yukihiro Matsumoto)
Updated by matz (Yukihiro Matsumoto) over 9 years ago
Accepted.
Matz.
Updated by nobu (Nobuyoshi Nakada) over 9 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]