ruby學習之Hash

來源:互聯網
上載者:User

標籤:hash

     定義

hsh=Hash.new

hsh=Hash[1=>”a”,2=>”b”]

hsh={“1”=>”a”,2=>”b”}

支援任意對象為key,習慣使用Symbol

 

二、常用方法

#!/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.1s]

三、尋找和迭代

Hash是可枚舉類型的對象,具有其搜尋遍曆和排序的能力,參見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.1s]

ruby學習之Hash

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.