我有一个数组,其中包含像"4.5"
这样的浮点字符串,以及像"Hello"
这样的常规字符串。我想对数组进行排序,以便常规字符串在末尾出现,类似浮点数的字符串在它们之前,并按浮点值排序。
我做了:
@arr.sort {|a,b| a.to_f <=> b.to_f }
答案 0 :(得分:1)
在ruby 1.9 +中排序
["1.2", "World", "6.7", "3.4", "Hello"].sort
将返回
["1.2", "3.4", "6.7", "Hello", "World"]
您可以对某些边缘情况使用@cary解决方案,例如[“10.0”,“3.2”,“嘿”,“世界”]
答案 1 :(得分:1)
arr = ["21.4", "world", "6.2", "1.1", "hello"]
arr.sort_by { |s| Float(s) rescue Float::INFINITY }
#=> ["1.1", "6.2", "21.4", "world", "hello"]
答案 2 :(得分:0)
又快又脏:
arry = ["1", "world", "6", "21", "hello"]
# separate "number" strings from other strings
tmp = arry.partition { |x| Float(x) rescue nil }
# sort the "numbers" by their numberic value
tmp.first.sort_by!(&:to_f)
# join them all in a single array
tmp.flatten!
可能适合您的需求