Use Hash#compact and Hash#compact! from Ruby 2.4

- Ruby 2.4 has added Hash#compact and Hash#compact! so we can use it
  now.
- Reference: https://bugs.ruby-lang.org/issues/11818 and https://bugs.ruby-lang.org/issues/12863.
上级 8447f8d0
* Use `Hash#compact` and `Hash#compact!` from Ruby 2.4. Old Ruby versions
will continue to get these methods from Active Support as before.
*Prathamesh Sonpatki*
* Fix `ActiveSupport::TimeZone#strptime`.
Support for timestamps in format of seconds (%s) and milliseconds (%Q).
......@@ -21,10 +26,10 @@
Time.zone = "US/Eastern"
t = Time.zone.local(2016,11,6,1)
# => Sun, 06 Nov 2016 01:00:00 EDT -05:00
# => Sun, 06 Nov 2016 01:00:00 EDT -05:00
t.in(1.hour)
# => Sun, 06 Nov 2016 01:00:00 EST -05:00
# => Sun, 06 Nov 2016 01:00:00 EST -05:00
Fixes #26580.
......
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 # => {}
# { c: true }.compact # => { c: true }
def compact
select { |_, value| !value.nil? }
unless Hash.instance_methods(false).include?(:compact)
# 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 # => {}
# { c: true }.compact # => { c: true }
def compact
select { |_, value| !value.nil? }
end
end
# Replaces current hash with non +nil+ values.
# Returns nil if no changes were made, otherwise returns the hash.
#
# hash = { a: true, b: false, c: nil }
# hash.compact! # => { a: true, b: false }
# hash # => { a: true, b: false }
# { c: true }.compact! # => nil
def compact!
reject! { |_, value| value.nil? }
unless Hash.instance_methods(false).include?(:compact!)
# Replaces current hash with non +nil+ values.
# Returns nil if no changes were made, otherwise returns the hash.
#
# hash = { a: true, b: false, c: nil }
# hash.compact! # => { a: true, b: false }
# hash # => { a: true, b: false }
# { c: true }.compact! # => nil
def compact!
reject! { |_, value| value.nil? }
end
end
end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册