tags:

views:

104

answers:

2

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.

+6  A: 

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

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

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)

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

as expected.

paxdiablo
I totally disagree. Zero isn't a positive number, and any reasonable programmer who had to read/modify your code would probably assume that 0.positive? and 0.negative? would both return false. After all, computer science is a branch of mathematics.
CaptainAwesomePants
zero? already exists :)
banister
@Captain, most normal people are neither computer scientists nor mathematicians :-)
paxdiablo
@banister: I use zero? myself, but is it for all versions of ruby, or only 1.8.7/1.9.1 or later?
Andrew Grimm
+1  A: 

0 is a Fixnum, try:

p 0.class

>> Fixnum

so, change class Number to class Fixnum

I dont know if you want to add this methods to floats/integers, but you could do something like this:

class Float
...your methods...
end

0.to_f.positive?

there are more possibilities to make this task, all depends on what type/class you want to add this methods

Sebastian Brózda
add it to `Numeric`
banister