ruby學習筆記(6)-Array的使用

來源:互聯網
上載者:User

ruby的數組基本使用,跟c#中的數組比起來,最不習慣的區別在於允許負索引(跟javascript到有幾分相似)

arr=[3,4,5,6,7,8,9]puts arr[0]  # 3puts arr.first  # 3puts arr[arr.length-1] # 9puts arr[arr.size-1] # 9puts arr.last  #9puts arr[-1] #9,下標為-1,即相當於取最後一個元素puts arr[-2] #8,倒著取第二個數print arr[1..3]   ,"\n" #456,取下標從1到3的元素print arr[-3,2]   ,"\n" #倒數第三個元素開始,連續取2個元素,即7,8

複雜一點的應用如下,這裡要特意指出的是,ruby中的數組天生就已經實現了堆棧與隊列,這一點想得很周到.

#來自"Ruby語言入門教程v1.0"中的E8.1-3.rbarr=[4,5,6]     print arr.join(", "),"\n" # 4, 5, 6arr[4] = "m" #將第5個元素賦值為mprint arr.join(", "),"\n" #第4個元素因為沒賦值,所以為空白,輸出結果為4, 5, 6, , mprint arr[3] ,"\n" #第4個元素為空白,所以輸出nilarr.delete_at(3) #刪除第4個元素    print arr.join(", "),"\n" #輸出 4, 5, 6, marr[2] = ["a","b","c"]  #將第3個元素"6",重新賦值為一維數組[a, b, c]puts arr[0] # 4puts arr[1] # 5puts arr[2] # a,b,c 注意:用puts輸出時,會自動把每個元素添加\nputs arr[3] # mprint arr.join(", "),"\n" # 4, 5, a, b, c, mprint arr[2] ,"\n" # abcarr[0..1] = [7,"h","b"]  #將前面二個元素4,5換成7,h,bprint arr.join(", "),"\n" # 7, h, b, a, b, c, marr.push("b" )  #將b壓入數組尾部  print arr.join(", "),"\n"# 7, h, b, a, b, c, m, barr.delete(["a","b","c"] )  #刪除數組中匹配["a","b","c"]的元素,即arr[2],注意前面的arr[2] = ["a","b","c"] print arr.join(", "),"\n" # 7, h, b, m, barr.delete("b")  #將所有b元素刪除   print arr.join(", "),"\n" # 7, h, marr.insert(2,"d") # 在第3個元素處插入d,如果後面還有元素,則索引後移print arr.join(", "),"\n" #7, h, d, marr<<"f"<<2  #將元素f,2加入到數組最後,類似前面的push用法print arr.join(", "),"\n" # 7, h, d, m, f, 2arr.pop #彈出一個元素,與前面的push結合起來,ruby中的數組本身就是一個堆棧print arr.join(", "),"\n" #7, h, d, m, farr.shift #元素左移一位,即實現了隊列print arr.join(", "),"\n" #h, d, m, farr.clear #清空元素print arr.join(", "),"\n"

最後講一個要注意的地方:array的each與delete一起用時,有時候會出現意想不到的效果!

#arr = [1,[2,3],2,3,4,5,6]print arr.join(","),"\n" #1,2,3,2,3,4,5,6arr.delete([2,3])print arr.join(","),"\n" #1,2,3,4,5,6arr.each{|x| arr.delete(x)};print arr.join(","),"\n" #2,4,6 注意這裡:array對象each,delete一起使用時,使用不當會把自身的"部分"元素給刪除掉
相關文章

聯繫我們

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