
even? and odd? methods in Integer class
Quote:
> Why Integer class doesn't have 'even?' nor 'odd?' method?
> Of course, it is easy to define by myself.
> But I wonder why these methods are not included in Ruby
> by default?
> ..--------------------
> class Integer
> def even?
> return self % 2 == 0
> end
> def odd?
> return self % 1 == 0
> end
> end
> ..--------------------
> I believe that these methods are very useful and friendly,
> especially for Web Designers.
> They're familiar with a concept about modulo, but not familiar
> with an operator of modulo (= '%').
> ..--------------------
> <% count = 0 %>
> <% for item in list do %>
> <% count += 1 %>
> <% if count % 2 == 0 then %> <!-- count.even? is more hopeful -->
> <tr class="even">
> <td><%=item%></td>
> </tr>
> <% else %>
> <tr class="odd">
> <td><%=item%></td>
> </tr>
> <% end %>
> <% end %>
> ..--------------------
> I hope these methods are to be built-in methods.
> Give your opinion, please.
Your odd? definition returns true for all ints.
All integers are 0 modulo 1.
You want self % 2 == 1:
irb(main):001:0> class Integer
irb(main):002:1> def odd?
irb(main):003:2> self % 1 == 0
irb(main):004:2> end
irb(main):005:1> end
nil
irb(main):006:0> 3.odd?
true
irb(main):007:0> 4.odd?
true
irb(main):008:0> class Integer
irb(main):009:1> def odd?
irb(main):010:2> self % 2 == 1
irb(main):011:2> end
irb(main):012:1> end
nil
irb(main):013:0> 3.odd?
true
irb(main):014:0> 4.odd?
false
Cheers,
Mike
--
"I want to die peacefully in my sleep like my Grandfather...
... not screaming and yelling like the passengers in his car"