Convenient methods for the Ruby Number and 0 class

I write convenient methods to check if a number is positive or negative, for example:

class Numeric def positive? self > 0 end def negative? self < 0 end end 

but in this case I do not know how to handle such cases:

 >> 0.positive? >> 0.negative? 

Refresh . I updated a typo in the class name. I used a numerical value because I also needed to check the floats.

+4
source share
3 answers

If the problem is that you get false for both, you either consider 0 positive or not. If so, you should have something like:

 def positive? self >= 0 end 

If not, leave it as it is, since 0 not positive, but negative, and you should return false for both.

However, if the problem is that you are getting errors with 0.positive? (much more likely), the reason you get the problem is because 0 is FixNum , not Number . You can see this with the following message:

 testprog.rb:12: undefined method `positive?' for 0:Fixnum (NoMethodError) 

You should probably add it to FixNum yourself, or Integer or Numeric , the base class for various number types, such as FixNum and BigNum . Where you enter your convenience methods depends on how widely they are available to you.

For example, if you change the code to the following (here I include the 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 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 

as was expected.

+7
source

Ruby 2.3 introduced Numeric#positive? and Numeric#negative? if you are on Ruby 2.3+, you should use these two instead.

+9
source

0 is Fixnum, try:

 p 0.class 

β†’ Fixnum

therefore, change the Number class to the Fixnum class

I don't know if you want to add these methods to float / integers, but you can do something like this:

 class Float ...your methods... end 0.to_f.positive? 

there are more possibilities for this task, it all depends on what type / class you want to add these methods.

0
source

All Articles