From 51215937874dd5e8705701c772b41a7ce522f67c Mon Sep 17 00:00:00 2001 From: tinogomes Date: Wed, 8 Jan 2014 15:46:42 -0200 Subject: Adding Hash#compact and Hash#compact! methods * Adding Hash#compact and Hash#compact! methods * Using Ruby 1.9 syntax on documentation * Updating guides for `Hash#compact` and `Hash#compact!` methods * Updating CHANGELOG for ActiveSupport * Removing unecessary protected method and lambda for `Hash#compact` implementations * Performing `Hash#compact` implementation - https://gist.github.com/tinogomes/8332883 * fixing order position * Fixing typo --- activesupport/lib/active_support/core_ext/hash.rb | 1 + .../lib/active_support/core_ext/hash/compact.rb | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/hash/compact.rb (limited to 'activesupport/lib/active_support') diff --git a/activesupport/lib/active_support/core_ext/hash.rb b/activesupport/lib/active_support/core_ext/hash.rb index 686f12c6da..f68e1662f9 100644 --- a/activesupport/lib/active_support/core_ext/hash.rb +++ b/activesupport/lib/active_support/core_ext/hash.rb @@ -1,3 +1,4 @@ +require 'active_support/core_ext/hash/compact' require 'active_support/core_ext/hash/conversions' require 'active_support/core_ext/hash/deep_merge' require 'active_support/core_ext/hash/except' diff --git a/activesupport/lib/active_support/core_ext/hash/compact.rb b/activesupport/lib/active_support/core_ext/hash/compact.rb new file mode 100644 index 0000000000..6566215a4d --- /dev/null +++ b/activesupport/lib/active_support/core_ext/hash/compact.rb @@ -0,0 +1,20 @@ +class Hash + # Returns a hash with non +nil+ values. + # + # hash = { a: true, b: false, c: nil} + # hash.compact # => { a: true, b: false} + # hash # => { a: true, b: false, c: nil} + # { c: nil }.compact # => {} + def compact + self.select { |_, value| !value.nil? } + end + + # Replaces current hash with non +nil+ values. + # + # hash = { a: true, b: false, c: nil} + # hash.compact! # => { a: true, b: false} + # hash # => { a: true, b: false} + def compact! + self.reject! { |_, value| value.nil? } + end +end -- cgit v1.2.3