Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/monkey_patch_happy/hash_patch.rb

Instance Method Summary collapse

Instance Method Details

#fetch_all(*args) ⇒ Object

example: => 1, “b” => 2, “c” => 3.fetch_all(:a, :b) => 1, “b” => 2, “c” => 3.fetch_all([:a, :b]) or [[:a, :b]]



5
6
7
8
9
10
# File 'lib/monkey_patch_happy/hash_patch.rb', line 5

def fetch_all(*args)
  #values_at不支持数组
  # args.flatten.map{|key| fetch(key)} #如果没找到该键值,会报错。
  #compact 去掉为nil的键
  args.flatten.map{|key| self[key]}
end

#format_hour_keyObject

not test



25
26
27
28
29
30
31
# File 'lib/monkey_patch_happy/hash_patch.rb', line 25

def format_hour_key
  new_hash = {}
  self.each do |key, value|
    new_hash[( "h" + (key.to_i + 1).to_s).to_sym] = value
  end
  new_hash
end

#format_key_to_sym(str) ⇒ Object

str = “h”, hash = {“01” => 1, “02” => 2 } result: {:h1 => 1, :h2 => 2 }



15
16
17
18
19
20
21
22
# File 'lib/monkey_patch_happy/hash_patch.rb', line 15

def format_key_to_sym(str)
  new_hash = {}
  self.each do |key, value|
    new_hash[(str + key.to_i.to_s).to_sym] = value if key.present?
  end
  # self = nil #release
  new_hash
end