Advertisement
applehelpwriter

Ruby Intro (mile/km conversion script)

Jan 21st, 2014
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.03 KB | None | 0 0
  1. #!/bin/ruby
  2.  
  3. #notice that this script uses 3 different kinds of commenting mechanisms. Can you spot all three?
  4.  
  5. #'puts' is like 'print' but also adds a newline
  6. puts "convert from mile or km?"
  7. #gets asks the user for input and saves it as a string in the local variable 'theScale'
  8. theScale = gets
  9. puts "how many?"
  10. #gets still saves the users input as a string, even though they input a number
  11. theNumber = gets
  12.  
  13. =begin
  14. 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;
  15. then we '.chomp' on the variable 'theScale' so we can test it for equivalence.
  16. Without chomping, the string would have some extra bites on the end that would make our equivalence test fail
  17. =end
  18.  
  19. theAnswer = (theNumber.to_i / 5.0 * 8) if theScale.chomp == "mile"
  20. theAnswer = (theNumber.to_i / 8.0 * 5) if theScale.chomp == "km"
  21.  
  22. #find out more at http://learnrubyonthemac.com
  23. puts "The answer is #{theAnswer}" #try figuring out how to add the distance unit to the end! :)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement