在Ruby中,哈希(Hash)是一種存儲鍵值對的數據結構。要查找哈希中的鍵對應的值,可以使用以下方法:
[]
操作符:hash = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }
value = hash["key1"] # value 的值為 "value1"
[]=
操作符:hash = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }
hash["key4"] = "value4" # 在哈希中添加新的鍵值對 "key4" => "value4"
fetch
方法:hash = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }
value = hash.fetch("key1") # value 的值為 "value1",如果 "key1" 不存在,則返回默認值(可選)
[]?
操作符:hash = { "key1" => "value1", "key2" => "value2", "key3" => "value3" }
value_present = hash["key1"]? # 返回 true,如果 "key1" 存在,否則返回 false
請注意,當使用[]
操作符和fetch
方法時,如果鍵不存在于哈希中,將引發KeyError
異常。為了避免這種情況,可以使用fetch
方法的第二個參數提供默認值,或者在調用[]
操作符時使用key?
方法檢查鍵是否存在。