ruby1.9 hash的变化

时间:2022-05-01 22:30:08

之前会对hash的键名进行排序:

h = {}
puts h
h[1] = 1
puts h
h[0] = 0
puts h # {0=>0,1=>1}

1.9就不会再排序:

h = {}
puts h
h[1] = 1
puts h
h[0] = 0
puts h # {1=>1,0=>0}
#http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/

更简洁的hash字面量:


h = {a: 2} #注意,冒号一定要紧靠键名
puts h
#http://www.oreillynet.com/ruby/blog/2007/06/on_the_horizon_ten_things_i_li.html
h = { a: 1, b: 2 }# 相当于下面的旧语法
puts h
h = { :a=> 1, :b=>2 }# 返回{:a=>1, :b=>2}
puts h