2015-10-21 95 views
0

我有一个阵列,其中包含类似floatl的字符串,如"4.5",以及像"Hello"这样的常规字符串。我想对数组进行排序,以便常规字符串到达​​最后,浮动状字符串在它们之前,并按浮点值排序。对具有普通字符串元素和“类似数字”的字符串元素的数组进行排序

我所做的:

@arr.sort {|a,b| a.to_f <=> b.to_f } 
+0

看看HTTP的解决方案:// apidock。 com/ruby​​/String/to_f,如果a不是有效的数字,则a.to_f将返回0.0,您将需要使用提供的块检查它。 – user2085282

回答

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"] 
+1

如果你想在最后排序的字符串也可以扩展到'[(Float(s)rescue Float :: INFINITY),s]'。 – matt

+0

好点,@Matt。 –

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! 

可能会满足您的需求

1

排序红宝石1.9+

["1.2", "World", "6.7", "3.4", "Hello"].sort 

将返回

["1.2", "3.4", "6.7", "Hello", "World"] 

可以使用@cary对某些边缘情况,例如[ “10.0”, “3.2”, “哎”, “世界”]

+0

'['10.0','9.0','猫']'? –

+0

是的,它不会工作,但我使用由op给出的值“4.5”,并根据我的答案。 – owade