[英]Sort an Array Mixed With Integers and Strings - Ruby
I have an array that must be sorted with low number to high number and then alphabetical order. 我有一个数组必须按低数字到高数字排序,然后按字母顺序排序。 Must use Array#sort_by
必须使用Array#sort_by
i_want_dogs = ["I", "want", 5, "dogs", "but", "only", "have", 3]
I want it to output: 我希望它输出:
=> [3,5,"I","but","dogs","have","only","want"]
I tried: 我试过了:
i_want_dogs.sort_by {|x,y| x <=> y }
I know that is obviously wrong, but I can't figure it out with the integers and the strings combined. 我知道这显然是错的,但我无法用整数和字符串组合来解决它。
Use the sort
method with a block that defines a comparator that does what you want. 将
sort
方法与定义比较器的块一起使用,该比较器可以执行您想要的操作。 I wrote a simple one that compares values when the classes are the same and class names when they are different. 我写了一个简单的例子,它在类相同时比较值,在不同时比较类名。
def comparator(x, y)
if x.class == y.class
return x <=> y
else
return x.class.to_s <=> y.class.to_s
end
end
Use it like this: 像这样使用它:
i_want_dogs.sort { |x, y| comparator(x, y) }
使用partition
将数字与字符串分开,分别对每个字符进行排序并加入最终结果,例如
i_want_dogs.partition { |i| i.is_a?(Fixnum) }.map(&:sort).flatten
This will give you the result: 这会给你结果:
i_want_dogs.sort_by {|x| x.to_s }
UPDATE: 更新:
Thanks @vacawama who points out that it will sort numbers alphabetically. 谢谢@vacawama指出它将按字母顺序对数字进行排序。 If you need to sort number by it's value, other answers will be something you need to try.
如果你需要按照它的值对数字进行排序,那么你需要尝试其他答案。
First you need to convert the elements in the array to a string. 首先,您需要将数组中的元素转换为字符串。 Try this
尝试这个
i_want_dogs.sort_by(&:to_s)
This will return 这将返回
[3,5,"I", "but", "dogs", "have", "only" "want"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.