标签:数组 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 }
标签:数组 shuffle div split ring his min 反转 最大
原文地址:https://www.cnblogs.com/ltns-hhyb/p/9079048.html