在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
.
我们把涉及人的姓名和年龄的一些信息,然后我们展示其中的一些。鉴于key(John”)已经发现,一切都很顺利。让我们试着查找一个不存在的key:
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