是不是在Ruby中消除负数
我是这里的新用户,也是Ruby的初学者。我需要从是不是在Ruby中消除负数,ruby,numeric,negative-number,Ruby,Numeric,Negative Number,我是这里的新用户,也是Ruby的初学者。我需要从是否为数字?中消除负值(数字)。所以代码是这样的: class String def is_number? true if Float(self) rescue false end end 这给了我正数和负数,而我只需要得到正数。有没有办法消除这个方法中的负数?如果没有,那么也可以采用其他方法。类似的方法应该可以: class String def is_number? f = Float(self) f &
是否为数字?
中消除负值(数字)。所以代码是这样的:
class String
def is_number?
true if Float(self) rescue false
end
end
这给了我正数和负数,而我只需要得到正数。有没有办法消除这个方法中的负数?如果没有,那么也可以采用其他方法。类似的方法应该可以:
class String
def is_number?
f = Float(self)
f && f >= 0
rescue
false
end
end
'1'.is_number? # => true
'-1'.is_number? # => false
'0.0'.is_number? # => true
'4.12'.is_number? # => true
'-10_000'.is_number? # => false
出于好奇,您为什么要写这行
Float(self)
?此行的必要性是什么?@iAmRubuuu:Float
如果字符串无法转换为数字,则函数会引发错误。
class String
def is_number?
Float(self) >= 0 rescue false
end
end