TKVR

Chris Pine, Learn to Program Chapter 4 - Mixing it Up

Feb 16th, 2012
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.77 KB | None | 0 0
  1. # conversions… computer doesn't know if we want to add 2 + 5 = 7 or 2 and 5 = 25, so need to convert var1 to a string in order to put 25
  2. var1 = 2
  3. var2 = '5'
  4.  
  5. puts var1.to_s + var2
  6. # and vice-versa to put 7 via conerting a string to an integer
  7. puts var1 + var2.to_i
  8.  
  9. # other conversions - note: computer ignores first thing it doesn't understand. rb.14/15
  10. puts '15'.to_f
  11. puts '99.999'.to_f
  12. puts '99.999'.to_i
  13. puts ''
  14. puts '5 is my favorite number!'.to_i
  15. puts 'Who asked you about 5 or whatever?'.to_i
  16. puts 'Your momma did.'.to_f
  17. puts ''
  18. puts 'stringy'.to_s
  19. puts 3.to_i
  20.  
  21. # Before  puts tries to write out an object, it uses to_s to get the string version of that object. In fact, the s in puts stands for string; puts really means put string.
  22. puts 20
  23. puts 20.to_s
  24. puts '20'
  25.  
  26. # gets and chomp methods
  27.  
  28. puts 'Hello there, and what\'s your name?'
  29. name = gets.chomp
  30. puts 'Your name is ' + name + '? What a lovely name!'
  31. puts 'Pleased to meet you, ' + name + '. :)'
  32.  
  33. # asks for a person's first name, then middle, then last. Finally, it should greet the person using their full name
  34. puts 'Hello! What\'s your first name?'
  35. firstName = gets.chomp
  36. puts 'Great! ' + firstName + ', what\'s your middle name?'
  37. middleName = gets.chomp
  38. puts 'OK, ' + firstName + ' ' + middleName + ', what\'s your last name?'
  39. lastName = gets.chomp
  40. puts 'Wonderful! Welcome to my domain, ' + firstName + ' ' + middleName + ' ' + lastName + '!'
  41.  
  42. # Write a program which asks for a person's favorite number. Have your program add one to the number, then suggest the result as a bigger and better favorite number.
  43. puts 'Yo dude, what\'s your favorite number?'
  44. number = gets.chomp
  45. new_number = number.to_i + 1
  46. puts 'OK. That\'s nice and all, but I reckon ' + new_number.to_s + ' is bigger and better.'
Add Comment
Please, Sign In to add comment