Please debug this program

B

brabuhr

I had to make a program to estimate the value of pi using Ramanujan's
method.

I have made the program but it is giving the following error

Question1.rb:8:in 'factorial':Interrupt

where 'factorial' is the name of the method and Question1.rb is the file
name.

Try this snippet, do you see the problem here?

def add(k)
i = 0
loop {
i += 1
if (i == k) then
return i
else
p i, k
end
sleep 1
}
end

k = gets
p add(k)
 
B

Brian Candler

Prateek said:
I had to make a program to estimate the value of pi using Ramanujan's
method.

I have made the program but it is giving the following error

Question1.rb:8:in 'factorial':Interrupt

You pressed ctrl-C?

I'm surprised it even ran at all:

def factorial(x)
if (x==0) then
return (1)
end
else
... something else

This doesn't make sense syntactically - an 'else' without an 'if'. You
need:

if x == 0
return 1
else
... something else
end
 
B

brabuhr

I'm surprised it even ran at all:

def factorial(x)
=A0if (x=3D=3D0) then
=A0 =A0return (1)
=A0 =A0end
=A0 =A0else
=A0 =A0 =A0... something else

This doesn't make sense syntactically - an 'else' without an 'if'.

An 'else' can live inside a method or a begin...end:
y:6: warning: else without rescue is useless
FOO
ELSE
FOO
y:3:in `foo': FOO (RuntimeError)
from y:9
def foo(n)
puts "FOO"
raise "FOO" if n
rescue
puts "RESCUE"
else
puts "ELSE"
end

foo(false)
foo(true)
FOO
ELSE
FOO
RESCUE


http://rubycentral.com/pickaxe/tut_exceptions.html
"The else clause is a similar, although less useful, construct. If
present, it goes after the rescue clauses and before any ensure. The
body of an else clause is executed only if no exceptions are raised by
the main body of code."
 
B

Brian Candler

Ugh, thanks - I'd forgotten the use of 'else' as part of a rescue, and
the implicit begin/end around a method body.
y:6: warning: else without rescue is useless

Matz send years ago that he regretted not making -w the default.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top