我正在研究如何摆弄Ruby中的特殊排序机制。我最终用Ruby改写了this neat JavaScript solution:
class SpecialStr
include Comparable
attr_accessor :str
def initialize (str)
@str = str
end
def <=> (other)
self_num, self_string = @str.split(' ')
other_num, other_string = other.str.split(' ')
self_num > other_num ? 1 : other_num > self_num ? -1 :
self_string > other_string ? -1 : 1
end
end
arr = ['2 xxx', '20 axxx', '2 m', '38 xxxx', '20 bx', '8540 xxxxxx', '2 z']
arr_object = []
arr.each { |str| arr_object << SpecialStr.new(str) }
arr_object.sort! { |x, y| y <=> x }
output_arr = []
arr_object.each { |obj| output_arr << obj.str}
puts output_arr
这具有所需的输出(数字递减,然后字符串递增):
8540 xxxxxx
38 xxxx
20 axxx
20 bx
2 m
2 xxx
2 z
但代码似乎不必要地复杂化。 (Ruby应该比JS更简洁!)所以我问自己(现在我问你),为什么我不能这样做呢?
def <=> (other)
self_num, self_string = self.split(' ')
other_num, other_string = other.split(' ')
self_num > other_num ? 1 : other_num > self_num ? -1 :
self_string > other_string ? -1 : 1
end
arr = ['2 xxx', '20 axxx', '2 m', '38 xxxx', '20 bx', '8540 xxxxxx', '2 z']
arr.sort! { |x, y| y <=> x }
puts arr
这输出错误,基于sort
,好像我没有重新定义<=>
:
8540 xxxxxx
38 xxxx
20 bx
20 axxx
2 z
2 xxx
2 m
这里的代码更短,但不起作用。它使用内置于Ruby的<=>
模块中的Comparable
版本,而不是我试图覆盖它。为什么我不能覆盖它?方法只能在类或模块内部重写吗?在Ruby中编写第一个脚本是否有更短的方法? (对不起,如果这是一个菜鸟问题,我是初学者。)