Class: Hash

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

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

Magic predicates. For instance:

options.force?                  # => !!options['force']
options.shebang                 # => "/usr/lib/local/ruby"
options.test_framework?(:rspec) # => options[:test_framework] == :rspec


8
9
10
11
12
13
14
# File 'lib/hash.rb', line 8

def method_missing(method, *args, &block)
  judge_mt = method.to_s.match(/^(\w+)\?$/)

  return (self[method] || self[method.to_s]) unless judge_mt
  value = self[judge_mt[1]] || self[judge_mt[1].to_sym]
  args.empty? ? !!value : (value == args.first)
end

Instance Method Details

#get_by_chain(chain_str) ⇒ Object

串联获取内部嵌套hash值

Parameters:

  • chain_str (String)

    嵌套取值表达式

Returns:

  • (Object)


19
20
21
22
23
# File 'lib/hash.rb', line 19

def get_by_chain(chain_str)
  chains = chain_str.split('.').map(&:to_sym)
  chains.keep_if {|k| k =~ /.+/}
  chains.inject(self) {|t, p| t && t.send(p)}
end