在Ruby中的Hash是一种数据结构,具有在 Key=> Value 价值。符号往往被用作key来加速键查找的过程。
Hash类提供了许多有用的方法,其中一些来自Enumerable module。我们不会记住这个类的所有方法,但是Hash类有一个很重要的方法 :default()
Ruby 基本的Hash表示方法:
people = Hash.new
people["Mary"] = 78
people["John"] = 21
people["Frank"] = 52
puts "Name: John, age: #{people["John"]}."
得到结果
Name:
John, age:
21
.
people = Hash.new
people["Mary"] = 78
people["John"] = 21
people["Frank"] = 52
puts "Name: George, age: #{people["George"]}."
puts people["George"].inspect
得到的结果是:
Name:
George, age: .
nil
standard_hash = Hash.new
puts standard_hash.default
our_hash = Hash.new
our_hash.default = 185
puts our_hash.default
puts standard_hash[:hello]
nil
185
185