Ruby's Louvre

每天学习一点点算法

导航

ruby1.9 hash的变化

之前会对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

posted on 2011-04-04 14:53  司徒正美  阅读(1236)  评论(0编辑  收藏  举报