开发者

How do I sort a Ruby array of strings by length?

开发者 https://www.devze.com 2023-01-05 20:06 出处:网络
How do开发者_StackOverflow中文版 I sort this: arr = [\"aaa\",\"aa\",\"aaaa\",\"a\",\"aaaaa\"]; Into this?

How do开发者_StackOverflow中文版 I sort this:

arr = ["aaa","aa","aaaa","a","aaaaa"];

Into this?

arr = ["a","aa","aaa","aaaa","aaaaa"];


arr = arr.sort_by {|x| x.length}

Or in 1.8.7+:

arr = arr.sort_by(&:length)


You can also use sort:

arr.sort{|x, y| x.length <=> y.length}


arr = arr.sort{|x,y| x.length - y.length} works too.

0

精彩评论

暂无评论...
验证码 换一张
取 消