I,
Definition:
HSH = hash. New
HSH = hash [1 => "A", 2 => "B"]
HSH = {"1" => "A", 2 => "B "}
Any object is supported as the key, and you are used to using symbol.
Ii. Common Methods
#!/usr/bin/ruby def printResult(args) print args puts "" endhsh={:a=>"hello",:b=>"world"} puts hsh # hsh.clear() # puts hsh hsh.delete(:a) puts hsh hsh[:c]="third" puts hsh hsh.delete_if(){|key,value| value=="third"} puts hsh puts hsh.has_key?(:b) puts hsh.has_value?("world") puts hsh.invert() hsh[:d]="ddd" hsh[:e]="eee" printResult hsh.keys() printResult hsh.values printResult hsh.values_at(:b,:d) puts hsh.length() puts hsh.merge({:b=>"bbbb",:f=>"ffff"}) puts hsh.replace({:b=>"b2b2b2",:g=>"ggg"}) print hsh.to_a()
Result:
{: A => "hello",: B => "world "}
{: B => "world "}
{: B => "world",: c => "third "}
{: B => "world "}
True
True
{"World" =>: B}
[: B,: D,: E]
["World", "DDD", "eee"]
["World", "DDD"]
3
{: B => "BBBB",: D => "DDD",: E => "eee",: F => "ffff "}
{: B => "b2b2b2",: g => "ggg "}
[[: B, "b2b2b2"], [: G, "ggg"] [finished in 0.1 s]
Iii. Search and iteration
Hash is an enumerated object with search traversal and sorting capabilities. For more information, see Ruby enumerable.
#!/usr/bin/ruby def printResult(args) print args puts "" endhsh={:a=>1,:b=>2,:c=>5,:d=>4} printResult hsh.find_all(){|key,value| value > 2} printResult hsh.map { |key,value| key } printResult hsh.max printResult hsh.sort printResult hsh.sort_by(){|key,value| value}hsh.each do |key,value| print key end puts "" hsh.each_key() do |key| print key end puts "" hsh.each_value() do |value| print value end
Result:
[[: C, 5], [: D, 4]
[: A,: B,: C,: d]
[: D, 4]
[[: A, 1], [: B, 2], [: C, 5], [: D, 4]
[[: A, 1], [: B, 2], [: D, 4], [: C, 5]
ABCD
ABCD
1254
[Finished in 0.1 s]
Hash of Ruby Learning