Tuesday, December 1, 2009

Ruby open class in Rails application, extending Fixnum,Array,Date,String Class

1. Make a library file(suppose "your_extension.rb") into your project's lib folder

2. require File.join(RAILS_ROOT,'lib/your_extension.rb')
- Add the above line at the End of environment.rb file

3.Suppose you want to extend Ruby Fixnum Class with your mehtods(named prime?) then PASTE the following code into "your_extension.rb"

class Fixnum
  def prime?
    n = self
    counter = 0
    1.step(n,1) {|i|
      if(n%i == 0)
        counter += 1
    if(counter == 2)
      return true
      return false

4. Restart your Rails application and you are done!
5. Now you can call prime? method from anywhere of your Rails application like
2.prime? -- returns true
5.prime? -- returns true
10.prime? -- returns false


  1. What a horrible implementation for checking for primality! Try this on for size instead:

    class Fixnum
    def prime?
    !( 2.upto(self/2).any? {|n| self % n == 0} ) unless self < 2

    Any number bigger than half the number you're checking obviously isn't going to divide your number, so we can stop at self/2 instead of going ALL the way up. Additionally, once you've found a factor, you don't need to keep checking more numbers above that because we've already determined that the number is not prime.

    I don't know why blogspot insists on stripping my indentation, but you can fix this easily enough when you pase this into your project. The method itself should be a one-liner, and I don't know if blogspot is going to want to wrap it until after I post.

    1. Hi James, Thank you for the comment I actually tried to explain how a ruby class can be extended but to write a prime number algorithm was not my concern :P

    2. Hi James,

      You might want to re-read your posts before clicking "Publish" in the future. Calling someone's code "horrible" doesn't really achieve much.

      Does it make anyone value your own code more?

      Does it help you convince the author that your approach might be better?

      Does it make you look like a jerk to *everyone* who comes across this page on the internet?

      So just, ya know, be a bit more mindful of what you're saying. You could convey exactly the same information nicely, and then someone stumbling here from a Google search would say, "hey, James McWolf writes good code and knows how to communicate it" instead of, "hey, James McWolf is kind of a dick."

      Incidentally, as Abdul noted, you might have missed the fact that the method implementation was completely irrelevant to the post.

      Abdul -- Thanks for the post; it helped me out!

      Best wishes,