Programming Ruby讀書筆記(二)

來源:互聯網
上載者:User

1.再談ruby數組。 class Test

 a = [1, 3, 5, 7, 9] puts a[0]     #----->1 puts a[-2]    #----->7 puts a[1, 3]   #----->[3, 5, 7] puts a[-3, 2]   #----->[5, 7] puts a[1..3]   #----->[3, 5, 7] puts a[1...3]   #----->[3, 5]  a[2] = 'cat'   #----->[1, 3, "cat", 7, 9] a[3, 2] = 'dog'  #----->[1, 3, "cat", "dog"] a[3, 1] = 'bee'  #----->[1, 3, "cat", "bee"] a[3, 0] = 'bat'  #----->[1, 3, "cat", "bat", "bee"] a[0...2] = []   #----->["cat", "bat", "bee"] a[4..5] = 99, 98 #----->["cat", "bat", "bee", nil, 99, 98]  end

數組的一些常用方法:

class Test  a = [0, 1, 2, 3, 4] b = Array.new(5) { |i| i * i }  #---------->[0, 1, 4, 9, 16] c = a & b             #---------->[0, 1, 4] d = a - b             #---------->[2, 3] e = a + b             #---------->[0, 1, 4, 2, 3] f = c[0..1] << d << c[2]     #---------->[0, 1, 2, 3, 4]  a.collect! { |x| x + 1 }     #---------->[1, 2, 3, 4, 5] a[6..7] = 7, 8          #---------->[1, 2, 3, 4, 5, nil, 7, 8] a.delete(7)            #a--------->[1, 2, 3, 4, 5, nil, 8] a.compact!            #---------->[1, 2, 3, 4, 5, 8] a.push 9             #---------->[1, 2, 3, 4, 5, 8, 9] a.pop               #---------->[1, 2, 3, 4, 5, 8] m = a.last(3)           #---------->[4, 5, 8] m.join("-")            #---------->"4-5-8" n = a.first(2)          #---------->[1, 2] n.unshift(-1, 0)         #---------->[-1, 0, 1, 2] n.shift              #---------->[0, 1, 2]   t = %w{ a b c d } t.insert(2, 99)          #---------->[a, b, 99, c, d] t.insert(-2, 1,2,3)        #---------->[a, b, 99, c, 1, 2, 3, d] t.insert(-1, "e")         #---------->[a, b, 99, c, 1, 2, 3, d, e] end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.