在Ruby中,哈希(Hash)是一種存儲(chǔ)鍵值對(duì)的數(shù)據(jù)結(jié)構(gòu)。要查找哈希中的鍵對(duì)應(yīng)的值,可以使用以下方法:
[]
操作符:hash = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }
value = hash["key1"] # value 的值為 "value1"
[]=
操作符:hash = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }
hash["key4"] = "value4" # 在哈希中添加新的鍵值對(duì) "key4" => "value4"
fetch
方法:hash = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }
value = hash.fetch("key1") # value 的值為 "value1",如果 "key1" 不存在,則返回默認(rèn)值(可選)
[]?
操作符:hash = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }
value_present = hash["key1"]? # 返回 true,如果 "key1" 存在,否則返回 false
請(qǐng)注意,當(dāng)使用[]
操作符和fetch
方法時(shí),如果鍵不存在于哈希中,將引發(fā)KeyError
異常。為了避免這種情況,可以使用fetch
方法的第二個(gè)參數(shù)提供默認(rèn)值,或者在調(diào)用[]
操作符時(shí)使用key?
方法檢查鍵是否存在。