Sunday, April 10, 2016

Ruby_Lesson_Putting the Form in Formatter

Methods,Methods Everywhere
1.What You'll Be Building
This project will help you create a small program that will read a user's input and correct his or her capitalization. Users can provide an almost infinite range of input, so it makes our lives easier as programmers to make their input standard before doing anything with it.
2.Prompting the User
In order to get input from the user, we'll first need to print a prompt on the screen.
print the question "What's your first name?" to the screen.
3.Getting Input 
variable_name = gets.chomp
gets is the Ruby method that gets input from the user. When getting input, Ruby automatically adds a blank line (or newline) after each bit of input; chomp removes that extra line. (Your program will work fine without chomp, but you'll get extra blank lines everywhere.)
Declare a variable first_name and set it equal to gets.chomp.
first_name = gets.chomp
4.Repeat for More Input
Add print prompts, variables, and gets.chomps for the user's last name, city, and state/province. Use last_name as the variable for the user's last name, city for their city, and state for their state or province.
5.Printing the Output
If you define a variable monkey that's equal to the string "Curious George", and then you have a string that says "I took #{monkey} to the zoo", Ruby will do something called string interpolation and replace the #{monkey} bit with the value of monkey—that is, it will print "I took Curious George to the zoo". We can do the same thing here! For example:
first_name = "Kevin"
puts "Your name is #{first_name}!"
will print "Your name is Kevin!"
puts "Your first name is #{first_name}, your last name is #{last_name}, you are from #{city},#{state}"
6.Formatting with String Methods
print "This is my question?"
answer = gets.chomp
answer2 = answer.capitalize 
answer.capitalize!
  • First we introduce one new method, capitalize, here. It capitalizes the first letter of a string and makes the rest of the letters lower case. We assign the result to answer2
  • The next line might look a little strange, we don't assign the result of capitalize to a variable. Instead you might notice the ! at the end of capitalize. This modifies the value contained within the variable answer itself. The next time you use the variable answer you will get the results of answer.capitalize
6.1.After each variable assignment: first_name, last_name, and city add the .capitalize! method.
first_name.capitalize!
6.2For state use the .upcase! method.
state.upcase!






No comments :

Post a Comment