开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜