Module: HashUtil
- Extended by:
- HashHelper
- Defined in:
- lib/hash_util.rb,
lib/hash_util/version.rb
Overview
Ruby Hash utility module
Constant Summary collapse
- VERSION =
"1.6"
Class Method Summary collapse
-
.add_hash2_to_hash1(a1, b1) ⇒ Object
adds hash2 value to hash1 value recursively alternate implementation using a string instead of hash can be found in hash helper module.
-
.extract_numbers_hash(str) ⇒ Object
extracts all numbers in a hash string.
-
.merge(hash_str1, hash_str2) ⇒ Object
copies values from a hash string in to another The 2 hashes should be of same structure but keys can be different FIXME rubocop.
-
.zero(obj) ⇒ Object
set all values in the hash to 0 This method should be moved to helper module and another genericmethod called set_Values to be added that can set all values including zero TODO optimize FIXME rubocop.
Methods included from HashHelper
add_hash_if_array, add_hash_if_hash, tokenize
Class Method Details
.add_hash2_to_hash1(a1, b1) ⇒ Object
adds hash2 value to hash1 value recursively alternate implementation using a string instead of hash can be found in hash helper module
13 14 15 16 17 18 19 20 21 |
# File 'lib/hash_util.rb', line 13 def self.add_hash2_to_hash1(a1, b1) if a1.class.name == 'Array' add_hash_if_array(a1, b1) elsif a1.class.name == 'Hash' add_hash_if_hash(a1, b1) else a1[k] += b1[k] end end |
.extract_numbers_hash(str) ⇒ Object
extracts all numbers in a hash string
74 75 76 77 78 79 80 81 82 |
# File 'lib/hash_util.rb', line 74 def self.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 |
.merge(hash_str1, hash_str2) ⇒ Object
copies values from a hash string in to another The 2 hashes should be of same structure but keys can be different FIXME rubocop
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/hash_util.rb', line 55 def self.merge(hash_str1, hash_str2) # extract nums, words token1 = hash_str1.scan(/[[+-]?([0-9]*[.])?[0-9e-]+]+|\w+|[{}\[\]:,"\040]/) token2 = extract_numbers_hash(hash_str2) j = 0 token1.each_index do |i| begin # used Float instead of to_f as to_f converts string to '0' Float token1[i] token1[i] = token2[j] j += 1 rescue end end token1.join.gsub(/\s+/, ' ') end |
.zero(obj) ⇒ Object
set all values in the hash to 0
This method should be moved to helper module and
another genericmethod called set_Values to be added
that can set all values including zero
TODO optimize
FIXME rubocop
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/hash_util.rb', line 31 def self.zero(obj) if obj.class.name == 'Array' obj = obj.collect do |m| %w[Array Hash].include?(m.class.name) ? zero(m) : 0 end elsif obj.class.name == 'Hash' obj.each do |k, _v| obj[k] = if %w[Array Hash].include?(obj[k].class.name) zero(obj[k]) else 0 end end else obj[k] = 0 end end |