Script 1: Mile/Km conversion tool

#!/bin/ruby

#notice that this script uses 3 different kinds of commenting mechanisms. Can you spot all three?

#'puts' is like 'print' but also adds a newline
puts "convert from mile or km?"

#'gets' asks for input and saves it as a string in the local variable 'theScale'
theScale = gets
puts "how many?"

#'gets' still saves the user input as a string, even though they input a number
theNumber = gets

=begin
because 'theNumber' is a string and not an integer, we have to first convert 'theNumber' to an integer using '.to_i' in order to do math on it;
then we '.chomp' on the variable 'theScale' so we can test it for equivalence.
Without chomping, the string would have some extra bites on the end that would make our equivalence test fail
=end

theAnswer = (theNumber.to_i / 5.0 * 8) if theScale.chomp == "mile"
theAnswer = (theNumber.to_i / 8.0 * 5) if theScale.chomp == "km"

#this next line uses 'string interpolation' to insert the variable into the string. To insert variable, we use a '#' and enclose the variable name in curly braces
puts "The answer is #{theAnswer}"

#Challenge: can you figure out how to add the distance unit to the end
#so that it reads 'The answer is 100 Kms' or 'The answer is 100 miles'?
#You'll need a couple of those 'if' modifiers you saw earlier and an extra variable interpolated in the string.



See The Answer Here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s