ruby picture

RCR 337: Integer#odd?, #even?

Submitted by Vince (Fri May 26 17:15:37 UTC 2006)

Abstract

It would make programs clearer if one could use odd? or even? to check the parity of an integer.

Problem

It is often useful to check if an integer is even or odd. While using
 if i % 2 == 0 
does work fine, it would be way better, for readability, if we could write
 if i.even?

Proposal

I propose to add two functions to the class Integer: Integer#odd? and Integer#even? that do what they sound to.

Analysis

This RCR doesn't break a single thing and should be fairly trivial to implement.

Implementation

 class Integer
   def even?
     return self % 2 == 0
   end
   def odd?
     return self % 2 == 1
   end
 end
ruby picture
Comments Current voting
This is something that's so simple and straightforward that when I came to Ruby, I expected it to be there already -- Daniel Schierbeck


This has been suggested so many times that I think Matz should just give in so as not to hear it suggested again ;)


Yeah i also think its a good idea to have this - shev


Strongly opposed 0
Opposed 0
Neutral 0
In favor 9
Strongly advocate 6
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .