Read sections 2.1-2.4 in chapter 2 of the textbook Explorations in Computing and read pages 19-42 of chapter 2 of the book Blown To Bits.
3 * 4 + 5 12 + 5 17HINT: You can check your final answers with irb!!!
def compute_period(length, gravity_accel) # computes period of simple pendulum given the string length in meters # and the acceleration due to gravity in meters/sec/sec (e.g. 9.8) return 2 * Math::PI * Math.sqrt(length / gravity_accel) end
compute_period(10, 9.8)
Will we get an integer result or a floating point result? Why?
compute_period(10)
Does the method use a default value for the acceleration due to gravity or does Ruby complain about this function call? Explain.
compute_period(9.8, 10)
Does Ruby report an error? Why or why not?
def compute_period(length, gravity_accel) # computes period of simple pendulum given the string length in meters # and the acceleration due to gravity in meters/sec/sec (e.g. 9.8) print 2 * Math::PI * Math.sqrt(length / gravity_accel) end
What value is stored in the variable period if we execute the following instruction? Why?
period = compute_period(10, 9.8)
def mystery(n) value = 1 for i in 1..n do value = value * 2 print value print "\n" # print a newline character end end
mystery(7)
value = value * i
What does this revised method display if we call it as follows:
mystery(7)
def mystery(n) value = 1 for i in 1..n do value = value * 2 return value end end
Store the function in a file, then load it in irb and call it with different positive integers and observe the results. What do your observations suggest about how the return statement works?