说完数组,就知道下一个肯定是哈希,在 Objective-C 里的体现是字典(NSDictionary)。为什么这种集合很受欢迎呢?这要从哈希算法说起,简单的说,hash 能以 O(1)的复杂度将内容映射到位置。Hash 算法的原理和基础概念,不乏好文,此处不赘述。后面可以专门复习梳理下。
创建哈希
?> hash = {}
=> {}
>> hash['1'] = "one"
=> "one"
?> hash
=> {"1"=>"one"}
>>
?> h = Hash.new
=> {}
>> h['2'] = "two"
=> "two"
>> h
=> {"2"=>"two"}
1
2
3
4
5
6
7
8
9
10
11
12
13
可以用 => 初始化 hash,可以叫它哈希火箭��(调皮)
?> h = {
?> '1' => "one",
?> '2' => "two"
>> }
=> {"1"=>"one", "2"=>"two"}
>> h
=> {"1"=>"one", "2"=>"two"}
1
2
3
4
5
6
7
如果取没有 key 的值,返回 nil。当然这取决于你构造时有没有传默认值。
?> h["3"]
=> nil
?> h = Hash.new(0)
=> {}
>> h['4']
=> 0
1
2
3
4
5
6
7
删除,简单的置值为 nil 不能删除。可以使用#delete方法
?> h = {'1' => "one", '2' => "two"}
=> {"1"=>"one", "2"=>"two"}
>> h.size
=> 2
>> h['1'] = nil
=> nil
>> h.size
=> 2
>> h
=> {"1"=>nil, "2"=>"two"}
>> h.delete('1')
=> nil
>> h.size
=> 1
>> h
=> {"2"=>"two"}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
也可以使用一些表示作为键值,也可以不使用 => 创建哈希(使用冒号,这和 Objective-C 很相似)
?> h = {:one => 1, :two => 2}
=> {:one=>1, :two=>2}
>> h
=> {:one=>1, :two=>2}
>>
?> h = {one: 1, two: 2}
=> {:one=>1, :two=>2}
>> h
=> {:one=>1, :two=>2}
1
2
3
4
5
6
7
8
9
常用方法
基础方法
?> a = {"one" => "grac", "two" => "kanil"}
=> {"one"=>"grac", "two"=>"kanil"}
>>
?> a.keys
=> ["one", "two"]
>> a.values
=> ["grac", "kanil"]
>> a.length
=> 2
>> a.size
=> 2
1
2
3
4
5
6
7
8
9
10
11
has_key?
?> a = {"one" => "grac", "two" => "kanil"}
=> {"one"=>"grac", "two"=>"kanil"}
>> a.has_key? "one"
=> true
1
2
3
4
select
?> a = {"one" => "grac", "two" => "kanil"}
=> {"one"=>"grac", "two"=>"kanil"}
?> a.select { |k, v| k == "one"}
=> {"one"=>"grac"}
>>
?> a.select { |k, v| k == "one" || k == "two"}
=> {"one"=>"grac", "two"=>"kanil"}
1
2
3
4
5
6
7
to_a
?> a = {"one" => "grac", "two" => "kanil"}
=> {"one"=>"grac", "two"=>"kanil"}
?> a.to_a
=> [["one", "grac"], ["two", "kanil"]]
1
2
3
4
合并两个 Hash
>> { "one" => "grac" }.merge({ "two" => "kanil" })
=> {"one"=>"grac", "two"=>"kanil"}
1
2
fetch 和使用 [] 一样获取数组 value,但是如果没有会 raise 错误
?> a = {"one" => "grac", "two" => "kanil"}
=> {"one"=>"grac", "two"=>"kanil"}
>> a["three"]
=> nil
>> a.fetch("two")
=> "kanil"
>> a.fetch("three")
KeyError: key not found: "three"
from (irb):7:in `fetch'
from (irb):7
...
1
2
3
4
5
6
7
8
9
10
11
*
函数关键字参数传递
Ruby 不支持关键字参数,但可以使用 Hash 模拟出来
?> class Article
>> attr_accessor :name, :author, :price
>>
?> def initialize(params = {})
>> @name = params[:name]
>> @author = params[:author]
>> @price = params[:price]
>> end
>> end
=> :initialize
>> a = Article.new(name: "雾都", author: "tom", price: 12.5)
=> #
>>
?> a.name
=> "雾都"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
迭代
和数组很类似
?> hash = {name: "雾都", author: "tom", price: 12.5}
=> {:name=>"雾都", :author=>"tom", :price=>12.5}
>>
?> hash.each {|key, value| puts "#{key} => #{value}"}
name => 雾都
author => tom
price => 12.5
=> {:name=>"雾都", :author=>"tom", :price=>12.5}
————————————————
版权声明:本文为CSDN博主「GracKanil」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/grackanil/article/details/82191562