Class: Characterizable::BetterHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/characterizable/better_hash.rb

Direct Known Subclasses

Snapshot

Instance Method Summary collapse

Instance Method Details

#as_jsonObject



8
9
10
# File 'lib/characterizable/better_hash.rb', line 8

def as_json(*)
  to_hash
end

#reject(&block) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/characterizable/better_hash.rb', line 11

def reject(&block)
  inject(Characterizable::BetterHash.new) do |memo, ary|
    unless block.call(*ary)
      memo[ary[0]] = ary[1]
    end
    memo
  end
end

#select(&block) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/characterizable/better_hash.rb', line 19

def select(&block)
  inject(Characterizable::BetterHash.new) do |memo, ary|
    if block.call(*ary)
      memo[ary[0]] = ary[1]
    end
    memo
  end
end

#slice(*keep) ⇒ Object

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



29
30
31
32
33
34
35
36
# File 'lib/characterizable/better_hash.rb', line 29

def slice(*keep)
  inject(Characterizable::BetterHash.new) do |memo, ary|
    if keep.include?(ary[0])
      memo[ary[0]] = ary[1]
    end
    memo
  end
end

#to_hashObject

In Ruby 1.9, running select/reject/etc. gives you back a hash if RUBY_VERSION < ‘1.9’



5
6
7
# File 'lib/characterizable/better_hash.rb', line 5

def to_hash
  Hash.new.replace self
end