Class: CodeHash
- Inherits:
-
Object
- Object
- CodeHash
- Defined in:
- lib/ns_service_pack/code_hash.rb
Overview
用一致化方法根据key查值或反查,使用hash方法([]),如
code_hash = CodeHash.new({'普通会员'=>0, '高级会员'=>10})
code_hash['普通会员'] #=>0
dode_hash[0] #=>'普通会员'
相关概念:
key: 人可识别的编码,如‘普通会员’
value: 存入数据库的编码,一般为增加数据检索速度
规则:
* 键/值具有唯一性(符合大部分使用情况)
* 字符串键统一用字符串访问,而非符号,如code_hash['a'], not code_hash[:a] (因为很多键为汉字)
Instance Attribute Summary collapse
-
#data ⇒ Object
Returns the value of attribute data.
-
#invert_data ⇒ Object
Returns the value of attribute invert_data.
Instance Method Summary collapse
- #[](code) ⇒ Object
- #all ⇒ Object
-
#initialize(code_hash = {}) ⇒ CodeHash
constructor
A new instance of CodeHash.
- #keys ⇒ Object
- #values ⇒ Object
Constructor Details
#initialize(code_hash = {}) ⇒ CodeHash
Returns a new instance of CodeHash.
19 20 21 22 |
# File 'lib/ns_service_pack/code_hash.rb', line 19 def initialize(code_hash={}) @data = code_hash @invert_data = code_hash.invert end |
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
17 18 19 |
# File 'lib/ns_service_pack/code_hash.rb', line 17 def data @data end |
#invert_data ⇒ Object
Returns the value of attribute invert_data.
17 18 19 |
# File 'lib/ns_service_pack/code_hash.rb', line 17 def invert_data @invert_data end |
Instance Method Details
#[](code) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/ns_service_pack/code_hash.rb', line 24 def [](code) #Fix a bug on 20111115 #@data[code] || @invert_data[code]||"真的没找到呀![code=#{code.to_s}]" if @data.key?(code) @data[code] elsif @invert_data.key?(code) @invert_data[code] else "注意:没找到对应键[#{code.to_s}]的值!" end end |
#all ⇒ Object
36 37 38 |
# File 'lib/ns_service_pack/code_hash.rb', line 36 def all @data.merge(@invert_data) end |
#keys ⇒ Object
40 41 42 |
# File 'lib/ns_service_pack/code_hash.rb', line 40 def keys @data.keys end |
#values ⇒ Object
44 45 46 |
# File 'lib/ns_service_pack/code_hash.rb', line 44 def values @data.values end |