views:

1550

answers:

2

Before I set about to writing this myself, has anyone seen a ruby implementation of the following behavior?

puts 7.nextprime();     #=>  11
puts 7.previousprime(); #=>  5
puts 7.isprime();       #=> true

Obviously this kind of thing would be ugly for large numbers but for integers never exceeding a few thousand (the common instance for me) a sensible implementation is doable, hence the question.

+6  A: 

Ruby comes with a built-in Prime class that allows you to iterate through primes starting at 1, but I see no way to initialize it with a starting value other than 1, nor a predicate check to determine whether or not a number is prime. I'd say go for it, though you should keep in mind that math in Ruby can be slow and if performance is a factor you may be better off considering writing it as a C or Java extension. Here's an example of how to use RubyInline to generate primes in C.

Also, I suggest you avoid using the method name 7.isprime - the convention in Ruby is 7.prime?.

Brian Guthrie
thanks for the reminder on prime? I usually try to provide aliases using both conventions
dreftymac
+2  A: 

Take a look at the snippets found here. They could give you a headstart.

Maran