雜湊在ruby中是一種以 key 和 value 組成的資料結構。
profile = {name: 'Yen', age:'26'}
p profile
{:name=>"Yen", :age=>"26"}
profile = {name: 'Yen', age:'26'}
profile[:age] = 30
p profile[:age]
# 30
keys
跟values
可以取得整個 hash 的 key 或 valuehash = {name: 'Yen', age:'26'}
p hash.keys
p hash.values
hash = {name: 'Yen', age:'26'}
p hash.has_key?(:name)
# true
p hash.has_value?(30)
# false
hash = {name: 'Yen', age:'26'}
p hash.key("26")
# age
Hash中在ruby裡面是一個物件,因此當我們複製hash的時候,其實並不是真的複製出來同一個,而是將兩個變數都指向同一個hash(共用同一個hash),還有陣列(array)也同樣會是call by reference
hash1 = {name: 'Yen', age:'26'}
hash2 = hash1
hash1[:age] = "50"
p hash2