2015-10-21 90 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