Create a file with the following code:
class Converter
def print_welcome
puts "Welcome to Converter!"
end
def convert_to_celsius(fahrenheit)
((fahrenheit - 32) * 5.0 / 9.0).round(2)
end
end
converter = Converter.new
converter.print_welcome
celsius = converter.convert_to_celsius(32)
puts "32 degrees F is #{celsius} degrees C"
celsius = converter.convert_to_celsius(212)
puts "212 degrees F is #{celsius} degrees C"
fahrenheit = converter.convert_to_fahrenheit(0)
puts "0 degrees C is #{fahrenheit} degrees F"
fahrenheit = converter.convert_to_fahrenheit(100)
puts "100 degrees C is #{fahrenheit} degrees F"
-
Run this code and you will see an error. Try to do the bare minimum required to make that error go away, and you will get a different error. Continue this process until all your errors are gone. Then, when your program is running, try to get it to print out the correct temperatures. You should only add code to the
Converter
class. -
When your program is running correctly, pretend that you are Ruby and trace the sequence of execution through the program. What is the first line of code that Ruby looks at? How does Ruby know where to go next?
Run these four different versions of the Converter
. Then, answer the following questions.
class Converter
def print_welcome
puts "Welcome to Converter!"
end
def convert_to_celsius(fahrenheit)
celsius = ((fahrenheit - 32) * 5.0 / 9.0).round(2)
return celsius
end
end
converter = Converter.new
puts converter.convert_to_celsius(32)
class Converter
def print_welcome
puts "Welcome to Converter!"
end
def convert_to_celsius(fahrenheit)
((fahrenheit - 32) * 5.0 / 9.0).round(2)
end
end
converter = Converter.new
puts converter.convert_to_celsius(32)
class Converter
def print_welcome
puts "Welcome to Converter!"
end
def convert_to_celsius(fahrenheit)
1+1
["piglet", "kitten", "baby gorilla"]
99
((fahrenheit - 32) * 5.0 / 9.0).round(2)
end
end
converter = Converter.new
puts converter.convert_to_celsius(32)
class Converter
def print_welcome
puts "Welcome to Converter!"
end
def convert_to_celsius(fahrenheit)
return ((fahrenheit - 32) * 5.0 / 9.0).round(2)
1+1
["piglet", "kitten", "baby gorilla"]
99
end
end
converter = Converter.new
puts converter.convert_to_celsius(32)
- What is the difference in the behavior of these four versions?
- How does Ruby know what to return from a method?
- What happens when ruby sees the
return
keyword?