在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