Prime Numbers
March 23rd, 2007
This next snip was brought to my attention by Peter Cooper, of Ruby Inside fame. This snip is posted on DZone’s new snippet site, formerly Peter’s snippet site.
1 2 3 4 5 |
class Fixnum def prime? ('1' * self) !~ /^1?$|^(11+?)\1+$/ end end |
The method prime? is being mixed (via open class) in with Fixnum (a Ruby class) to extend it so that simple calls likes the follow now become possible:
1.prime? |
The method will return either true or false, depending if the number is a prime number or not. This is a prime :) example of the power of Ruby’s open class feature. You can add any method to any class that you choose. Also, it demonstrates Ruby’s conciseness – 1 line of code (regular expression!) and you can now call that method on any number.
If you have a favorite piece of Ruby/Rails code or have seen a piece, drop me a line at revans [at] robertrevans ]dot[ com and it may be featured here.
Update As Brian Smith pointed out in the comments, this isn’t a true mixin, as I stated, because the prime is not included with a module that is then include within the Fixnum Class. You see, Module’s don’t have instance methods as classes do, but if you include a Module within a class, those methods within the Module are “mixed in” with the Class that is including the Module.
1 Response to “Prime Numbers”
Sorry, comments are closed for this article.


March 23rd, 2007 at 03:59 PM
Technically, that’s not a mixin. Rather, it’s an example of utilizing the concept of “open classes.”