use*_*568 -5 ruby ruby-on-rails spaceship-operator
Ruby中'<==>'的含义是什么?
示例:代码来自以下类,用于比较格式中的数字x.x.x,
def <==>(other)
# Some code here
end
Run Code Online (Sandbox Code Playgroud)
以下代码来自此类命令数字,如x.x.x,
class Version
attr_reader :fst, :snd, :trd
def initialize(version="")
v = version.split(".")
@fst = v[0].to_i
@snd = v[1].to_i
@trd = v[2].to_i
end
def <=>(other)
return @fst <=> other.fst if ((@fst <=> other.fst) != 0)
return @snd <=> other.snd if ((@snd <=> other.snd) != 0)
return @trd <=> other.trd if ((@trd <=> other.trd) != 0)
end
def self.sort
self.sort!{|a,b| a <=> b}
end
def to_s
@sorted = @fst.to_s + "." + @snd.to_s + "." + @trd.to_s
#Puts out "#{@sorted}".
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
952 次 |
| 最近记录: |