ruby--數組常用方法

來源:互聯網
上載者:User

標籤:數組   shuffle   div   split   ring   his   min   反轉   最大   

一、max_by,min_by根據條件取出數組中的最大值最小值

1 str = "this is a string"2 arr = str.split(" ")3 p arr.min_by { |e| e.length } #"a"4 p arr.max_by { |e| e.length } # "string"

二、find 找出匹配的第一個元素

1 str = "this is a string"2 arr = str.split(" ")3 p arr.find { |e| e.length == 1 } # "a"

三、select 找出匹配的所有元素

1 str = "this is a string"2 arr = str.split(" ")3 p arr.select { |e| e.length > 1 } # ["this", "is", "string"]

 四、排序

arr = [11, 23, 43, 32]#排序arr.sort # [11,23,32,43]arr.sort! # a = [11,23,32,43]#反轉arr.reverse #[32,43,23,11]#亂序arr.shuffle #

 五、自訂排序

arr="this is a string".split(" ") #按元素長度降序arr.sort! { |a,b| b.length <=> a.length }     
#按元素長度升序
arr.sort! { |a,b| a.length <=> b.length }

 

ruby--數組常用方法

聯繫我們

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