Ruby 的 Number 类和 0 的便捷方法 [英] Convenience methods for Ruby's Number class and 0
问题描述
我正在编写方便的方法来检查数字是正数还是负数,如下所示:
I'm writing convenience methods to check if number is positive or negative like so:
class Numeric
def positive?
self > 0
end
def negative?
self < 0
end
end
但在这种情况下我不知道如何处理这样的情况:
but in this case I do not know how to handle cases like these:
>> 0.positive?
>> 0.negative?
更新:我更新了班级名称中的拼写错误.我使用数字是因为我还需要检查浮点数.
Update: I've updated the typo in the class name. I used numeric because I needed to check the floats as well.
推荐答案
如果问题是两者都得到 false
,那么您可以将 0
视为积极与否.如果是这样,你应该有类似的东西:
If the problem is that you're getting false
for both, either you consider 0
to be positive or not. If so, you should have something like:
def positive?
self >= 0
end
如果不是,就保持原样,因为 0
既不是正也不是负,你应该对两者都返回 false.
If not, leave it as it is, since 0
is neither positive not negative and you should return false for both.
但是,如果问题是 0.positive?
出现错误(更有可能),则出现问题的原因是 0
是 FixNum
,而不是 Number
.您可以通过以下消息看到这一点:
However if the problem is that you're getting errors with 0.positive?
(far more likely), the reason you're getting a problem is because 0
is a FixNum
, not a Number
. You can see that with the following message:
testprog.rb:12: undefined method `positive?' for 0:Fixnum (NoMethodError)
您可能应该将它添加到 Fixnum
本身,或 Integer
,或 Numeric
,各种数字类型的基类,如 FixNum
和 BigNum
.您在何处注入便利方法取决于您希望它们在多大范围内可用.
You should probably add it to Fixnum
itself, or Integer
, or Numeric
, the base class for various numeric types like FixNum
and BigNum
. Where you inject your convenience methods depends on how widely you want them available.
例如,如果您将代码更改为以下内容(我在此处包含测试代码):
For example, if you change your code to the following (I'm including test code here):
class Numeric
def positive?
self > 0
end
def negative?
self < 0
end
end
print " 0 positive?: ", 0.positive?,"\n"
print " 0 negative?: ", 0.negative?,"\n"
print " 0 zero? : ", 0.zero?,"\n\n"
print "99 positive?: ", 99.positive?,"\n"
print "99 negative?: ", 99.negative?,"\n"
print "99 zero? : ", 99.zero?,"\n\n"
print "-2 positive?: ", -2.positive?,"\n"
print "-2 negative?: ", -2.negative?,"\n"
print "-2 zero? : ", -2.zero?,"\n\n"
然后它工作正常,输出:
it then works fine, outputting:
0 positive?: false
0 negative?: false
0 zero? : true
99 positive?: true
99 negative?: false
99 zero? : false
-2 positive?: false
-2 negative?: true
-2 zero? : false
正如预期的那样.
这篇关于Ruby 的 Number 类和 0 的便捷方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!