Sha256: d436a166be81b74ebfab95d794586cf8e5a1892acdfd7c1e97d8695e09f08e9e

Contents?: true

Size: 1.03 KB

Versions: 3

Compression:

Stored size: 1.03 KB

Contents

module Characterizable
  class BetterHash < ::Hash
    # In Ruby 1.9, running select/reject/etc. gives you back a hash
    # if RUBY_VERSION < '1.9'
      def to_hash
        Hash.new.replace self
      end
      def as_json(*)
        to_hash
      end
      def reject(&block)
        inject(Characterizable::BetterHash.new) do |memo, ary|
          unless block.call(*ary)
            memo[ary[0]] = ary[1]
          end
          memo
        end
      end
      def select(&block)
        inject(Characterizable::BetterHash.new) do |memo, ary|
          if block.call(*ary)
            memo[ary[0]] = ary[1]
          end
          memo
        end
      end
      # I need this because otherwise it will try to do self.class.new on subclasses
      # which would get "0 for 1" arguments error with Snapshot, among other things
      def slice(*keep)
        inject(Characterizable::BetterHash.new) do |memo, ary|
          if keep.include?(ary[0])
            memo[ary[0]] = ary[1]
          end
          memo
        end
      end
    # end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
characterizable-0.1.2 lib/characterizable/better_hash.rb
characterizable-0.1.1 lib/characterizable/better_hash.rb
characterizable-0.1.0 lib/characterizable/better_hash.rb