ruby1.9 hash

原创文章,转载请注明来源并保留原文链接

Hash有序
Ruby1.8:

ruby-1.8.7-p299 > h = {}
 => {}
ruby-1.8.7-p299 > h[1] = 1
 => 1
ruby-1.8.7-p299 > h
 => {1=>1}
ruby-1.8.7-p299 > h[0] = 1
 => 1
ruby-1.8.7-p299 > h
 => {0=>1, 1=>1}

Ruby1.9

irb(main):001:0> RUBY_VERSION
=> "1.9.3"
irb(main):002:0> h = {}
=> {}
irb(main):003:0> h[1] = 1
=> 1
irb(main):004:0> h[0] = 0
=> 0
irb(main):005:0> h
=> {1=>1, 0=>0}
irb(main):006:0>

类似json的写法:

ruby1.8不支持
ruby1.9:

irb(main):001:0> RUBY_VERSION
=> "1.9.3"
irb(main):002:0> {a: 1}
=> {:a=>1}
irb(main):003:0> {a_b: 1}
=> {:a_b=>1}
irb(main):004:0> {a-b: 1}
SyntaxError: (irb):3: syntax error, unexpected tLABEL
irb(main):005:0> {"a": 1}
SyntaxError: (irb):4: syntax error, unexpected ':', expecting tASSOC

参考链接

ruby-19-internals-ordered-hash/
on_the_horizon_ten_things_i_li.html
ruby-1-9-hash-with-a-dash-in-a-key

Leave a Reply

Your email address will not be published. Required fields are marked *