Module: HashHelper

Included in:
HashUtil
Defined in:
lib/hash_helper.rb

Overview

Ruby Hash utility module

Instance Method Summary collapse

Instance Method Details

#add_hash_if_array(a1, b1) ⇒ Object

submethod used by add_hash2_to_hash1 if type Array



24
25
26
27
28
29
30
31
32
33
# File 'lib/hash_helper.rb', line 24

def add_hash_if_array(a1, b1)
  a1 = a1.enum_for(:each_with_index).collect do |m, index|
    if %w[Array Hash].include?(m.class.name)
      add_hash2_to_hash1(a1[index], b1[index])
    else
      m + b1[index]
    end
  end
  a1
end

#add_hash_if_hash(a1, b1) ⇒ Object

submethod used by add_hash2_to_hash1 if type Hash



36
37
38
39
40
41
42
43
44
# File 'lib/hash_helper.rb', line 36

def add_hash_if_hash(a1, b1)
  a1.each do |k, _v|
    if %w[Array Hash].include?(a1[k].class.name)
      a1[k] = add_hash2_to_hash1(a1[k], b1[k])
    else
      a1[k] += b1[k]
    end
  end
end

#extract_numbers_hash(str) ⇒ Object

extracts all numbers in a hash string



13
14
15
16
17
18
19
20
21
# File 'lib/hash_helper.rb', line 13

def extract_numbers_hash(str)
  str = tokenize str
  # extract all nums including those using e notation
  str.select! { |m| /^[0-9.e-]+$/.match m }
  # used Float instead of to_f as to_f converts string to '0'
  str.collect do |m|
    Float m
  end
end

#tokenize(str) ⇒ Object



7
8
9
10
# File 'lib/hash_helper.rb', line 7

def tokenize(str)
  # extract words + nums
  str.scan(/[0-9.e-]+|\w+/)
end