#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
# 哈希(Hash)
# => 类似 "key" -> "Value" 这样的键值对集合.
# => 通常我们会使用符号或者字符串或者数值作为Hash的键.
# => 虽和数组类似, 但是却有一个重要的区别: Hash 的元素没有特定的顺序.
# 创建哈希
months = Hash.new
# 带有默认值的哈希
months2 = Hash.new("month")
puts "#{months2[0]}"
months2 = {"1" => "Jan"}
puts months2
符号
在 Ruby 中, 符号(symbol)与字符串对象很相似, 符号也是对象, 一般作为名称标签使用, 表示方法等的对象的名称.
要创建符号, 只需要在标识符的开头加上:
就可以了
sym = :foo # 表示符号 :foo
sym2 = :"foo" # 意思同上
符号能是实现的功能, 大部分字符串也能实现. 但在像Hash的键这样只是单纯判断"是否相等"的处理中, 使用符号会比字符串更加有效率, 因此在实际编程中我们也会时常用到符号.
另外, 符号与字符串可以相互转换. 对符号使用 to_s
方法, 则可以得到对应的字符串. 反之, 对字符串使用to_sym
方法, 则可以得到对应的符号.
changsaangdeMBP:~ changsanjiang$ irb --simple-prompt
>> sym = :foo
=> :foo
>> sym.to_s
=> "foo"
>> "foo".to_sym
=> :foo
>>
Hash的创建
Ruby 提供了一个专门的简短写法. 下面两行的意思相同.
changsaangdeMBP:~ changsanjiang$ irb --simple-prompt
>> person1 = {:name => "xiaoMing", :age => 20}
=> {:name=>"xiaoMing", :age=>20}
>> person2 = {name: "xiaoMing", age: 20}
=> {:name=>"xiaoMing", :age=>20}
>>
Hash的使用
取出对象
散列名[键]
保存对象
散列名[键] = 希望保存的对象
changsaangdeMBP:~ changsanjiang$ irb --simple-prompt
>> address = {name: "xiaoMing", age: 20}
=> {:name=>"xiaoMing", :age=>20}
>> address[:name]
=> "xiaoMing"
>> address[:age]
=> 20
>> address[:tel] = 132323232
=> 132323232
>> address
=> {:name=>"xiaoMing", :age=>20, :tel=>132323232}
>>
Hash的循环
使用 each 方法可以遍历散列中的所有元素, 逐个取出其元素的键和对应的值. 循环数组时, 是按索引顺序遍历元素, 循环散列时则是按照键值组合遍历元素.
语法如下:
散列.each do |键变量, 值变量|
# some code
end
changsaangdeMBP:~ changsanjiang$ irb --simple-prompt
>> address = {name: "xiaoMing", tel: 1323332}
=> {:name=>"xiaoMing", :tel=>1323332}
>> address.each do |key, value|
?> puts "key = #{key}, value = #{value}"
>> end
key = name, value = xiaoMing
key = tel, value = 1323332
=> {:name=>"xiaoMing", :tel=>1323332}
>>
网友评论