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.
精彩评论