Lon found this snippet this morning. It’s cool in a number of ways.
class Fixnum
def prime?
('1' * self) !~ /^1?$|^(11+?)\1+$/
end
end
First, it’s cool because it uses a regex to determine weather or not a number is prime. Second, it shows how trivial it is to add methods to a builtin abstract class. For example you can’t create an instance of it:
irb(main):001:0> n = Fixnum.new
NoMethodError: undefined method `new' for Fixnum:Class
from (irb):1
So how do I use it then?? Easy.
class Fixnum
def prime?
('1' * self) !~ /^1?$|^(11+?)\1+$/
end
end
puts 10.prime?
I prefer another way…
optimus = 7
puts optimus.prime?
Nice
Typo in your post. Last line should read “puts 10.prime?”.
Ok, for the Ruby-illiterate out there (me), can you pull that apart? Regexp to prime num test sounds broken.
David, good catch.
Patrick, I’ll do you one better. It was based on some Perl code:
http://montreal.pm.org/tech/neil_kandalgaonkar.shtml
that’s best written with //x expansion if ruby allows that. pretty slick lateral thinking, tho.