Ruby Hash
Contents
- Hash
- Hash key-value
Hash
Create hash {}, key => value
a = {"foo1" => 1, "foo2" => 2, "foo3" => 3} a["foo1"] # 1 a["foo2"] = 20 p a
Hash[]
Hash["apple", "fruit", "coffee", "drink"] #=> {"apple"=>"fruit", "coffee"=>"drink"}
Default value
a = Hash.new(5) a[:foo1] #=> 5
Not existed
nil
a = {} a[:rena] # nil
Use symbol as key
a = {:rena => 1, :jurina => 2, :manatsu => 3}
Hash key-value
[], keys, values, values_at, fetch, select
Name | Description |
---|---|
[]= | Change |
delete | Delete element(return deleted item) |
reject | Delete item of which block is true |
delete_if | Same above(break) |
replace | Replace hash |
shift | Remove key and value(1 set randomly) and return array |
merge | Merge hash and return it |
update | Integrate hash |
invert | Return hash which value and key are reversed |
clear | Clear data |
Examples
a = {"apple" => "iOS", "google" => "Android"} a["apple"] = "red" a["orange"] = "orange" a.delete("google") a = {"mayuyu" => "watanabe", "rena" => "matsui"} a.reject{|key, value| value == "matsui"} a.replace({"paruru" => "shimazaki", "kojiharu" => "kojima"})
shift method pick up randomly
Search Hash
ength, size, empty?, has_key?, include?, key?, member?, has_value, value?
length, size, empty?
a = {"apple" => "fruit", "coffee" => "drink"} a.size #=> 2 a.empty? #=> false
has_key?, include?, key?, member? : Check key existence
a = {"apple" => "iOS", "google" => "android"} a.value?("iOS") #=> true a.key?("microsoft") #=> false
Hath to Array
to_a