DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Validate An Odd Or Even Number In Ruby
x%2 == 0 ? true : false x = 5 x%2 == 0 ? true : false #=> false x = 8 x%2 == 0 ? true : false #=> true
or
Fixnum.class_eval { def even?; self%2 == 0 ? true : false; end }
133.even? #=> false
144.even? #=> true
Resources: - <a href="http://snippets.dzone.com/posts/show/2677">test for even and odd numbers</a> [dzone.com] - <a href="http://bmorearty.wordpress.com/2009/01/09/fun-with-rubys-instance_eval-and-class_eval/">Fun with Ruby’s instance_eval and class_eval « I like stuff.</a> [wordpress.com] *update: 24-Mar-2010 @11:45am* I've realised the condition can be shortened to x%2 == 0 e.g.
Fixnum.class_eval { def even?; self%2 == 0; end }
133.even? #=> false
144.even? #=> true





