我有一个阵列,其中包含类似floatl的字符串,如"4.5"
,以及像"Hello"
这样的常规字符串。我想对数组进行排序,以便常规字符串到达最后,浮动状字符串在它们之前,并按浮点值排序。对具有普通字符串元素和“类似数字”的字符串元素的数组进行排序
我所做的:
@arr.sort {|a,b| a.to_f <=> b.to_f }
我有一个阵列,其中包含类似floatl的字符串,如"4.5"
,以及像"Hello"
这样的常规字符串。我想对数组进行排序,以便常规字符串到达最后,浮动状字符串在它们之前,并按浮点值排序。对具有普通字符串元素和“类似数字”的字符串元素的数组进行排序
我所做的:
@arr.sort {|a,b| a.to_f <=> b.to_f }
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"]
如果你想在最后排序的字符串也可以扩展到'[(Float(s)rescue Float :: INFINITY),s]'。 – matt
好点,@Matt。 –
快速和肮脏的:
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.9+
["1.2", "World", "6.7", "3.4", "Hello"].sort
将返回
["1.2", "3.4", "6.7", "Hello", "World"]
可以使用@cary对某些边缘情况,例如[ “10.0”, “3.2”, “哎”, “世界”]
'['10.0','9.0','猫']'? –
是的,它不会工作,但我使用由op给出的值“4.5”,并根据我的答案。 – owade
看看HTTP的解决方案:// apidock。 com/ruby/String/to_f,如果a不是有效的数字,则a.to_f将返回0.0,您将需要使用提供的块检查它。 – user2085282