Ruby is_prime? method example


SUBMITTED BY: Guest

DATE: May 21, 2015, 1:48 p.m.

FORMAT: Ruby

SIZE: 689 Bytes

HITS: 807

  1. # Checking whether a number is prime can be
  2. # much simpler than this. But this example demonstrates
  3. # loop construct and duck-typing.
  4. # A simple duck-typing example.
  5. # Add a new method/functionality to an existing class
  6. class Fixnum
  7. def is_prime?
  8. (2..Math.sqrt(self).floor).each {|x| return false if self % x == 0 }
  9. return true
  10. end
  11. end
  12. loop do
  13. print "Enter a number (0 to exit): "
  14. num = gets.to_i
  15. break if num == 0
  16. puts "#{num} is" + (num.is_prime? ? " " : " NOT ") + "prime."
  17. end
  18. - See more at: http://www.chandrashekar.info/vault/ruby-scripts/loops.html#sthash.GbDNNtmh.dpuf

comments powered by Disqus