Hash of Ruby Learning

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.