Skip to content

Instantly share code, notes, and snippets.

@stephanschubert
Last active August 29, 2015 14:02
Show Gist options
  • Save stephanschubert/b8bf220f4e6c623ff8ef to your computer and use it in GitHub Desktop.
Save stephanschubert/b8bf220f4e6c623ff8ef to your computer and use it in GitHub Desktop.
Hash#compact removes all keys with nil as value.
Gem::Specification.new do |s|
s.name = 'compact'
s.version = '0.0.1'
s.platform = Gem::Platform::RUBY
s.author = 'Stephan Schubert'
s.email = '[email protected]'
s.summary = 'Hash#compact'
s.description = 'Removes all keys with nil as value.'
s.files = ['compact.rb']
s.test_file = 'compact_spec.rb'
s.require_path = '.'
s.add_development_dependency('rspec', ["~> 2.0"])
end
module Compact
def compact
delete_if { |k, v| v.nil? }
end
end
Hash.send :include, Compact
require File.expand_path('compact')
describe Compact do
let(:hash) { { a: nil, b: [5], c: "foo" } }
describe "#compact" do
subject { hash.compact }
it { should eq(b: [5], c: "foo") }
end
end
@stephanschubert
Copy link
Author

Instead of

{ a: 3, b: (5 if false) } #=> { a: 3, b: nil }

or

{ a:3 }.tap { |h| h[:b] = 5 if false } #=> { a:3 }

you can just use

{ a:3, b: (5 if false) }.compact #=> { a: 3 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment