Toggle navigation
Home
Latest pastes
FAQ
Random
BitBin is shutting down!
Register
Login
Ruby is_prime? method example
SUBMITTED BY:
Guest
DATE:
May 21, 2015, 1:48 p.m.
FORMAT:
Ruby
SIZE:
689 Bytes
Raw
Download
Tweet
HITS:
807
Go to comments
Report
# Checking whether a number is prime can be
# much simpler than this. But this example demonstrates
# loop construct and duck-typing.
# A simple duck-typing example.
# Add a new method/functionality to an existing class
class
Fixnum
def
is_prime?
(
2
..
Math
.
sqrt
(
self
)
.
floor
)
.
each
{
|
x
|
return
false
if
self
%
x
==
0
}
return
true
end
end
loop
do
print
"Enter a number (0 to exit): "
num
=
gets
.
to_i
break
if
num
==
0
puts
"
#{
num
}
is"
+
(
num
.
is_prime?
?
" "
:
" NOT "
)
+
"prime."
end
-
See
more
at
:
http
:
//
www
.
chandrashekar
.
info
/
vault
/
ruby
-
scripts
/
loops
.
html
#sthash.GbDNNtmh.dpuf
Please enable JavaScript to view the
comments powered by Disqus.
comments powered by
Disqus