Materials Presented
- Prompting the User
- gets
- .chomp
- .capitalize
- "!"
- "#{}" String Interpolation
When looking
for user input we would usually ask a questions like "How old
are you?" or "What's your favorite color?" To display
these questions we would input commands like the "puts" and
"print".
Examples:
- puts "What is your name?"
- print "What is your favorite color?"
Now we will
have to set a variable for the answer to these questions by a method
a called "gets". (Notice that there's no period in
front of this method, this probably means methods can contain
different symbols, characters, numbers, and mabye even spaces.) Using
a "gets" prompts the user to input a response and creates a
blank line after it, the same as a "puts" command does.
".chomp"
is a method that erases extra line that is created by "gets".
During some testing it looks like this only works with "gets"
and not with "puts".Example:
- Input: puts "What is your name?"
my_name = gets.chomp
Output: What is your name?
(asks for input here)
Once input is entered: (name entered)
".capitalize"
is a nifty method similiar to ".upcase" and ".downcase".
The ".capitalize" method makes the first letter of a string
uppercase and lowercases every letter after the first.
The thing about
".capitlize" is that it doesn't replace the original
string. Ruby makes a copy of what was suppose to be outputted,
capitilizes it, and then outputs the capitalized string. Adding "!"
to the end of ".capitalize" will replace the original
string and only keep the capitalized version.
- Input: print
"dAVID".capitalize
Ruby: dAVID
David
Output: David - Input: print
"dAVID".capitalize!
Ruby: dAVID
David
deletes dAVID (this is how I imagine the process to be)
Output: David
I don't really know what the point of getting rid of the extra line of code is, it doesn't seem to affect the output. My best guess is that in a larger program or website with millions of users those extra lines would add up quite fast and would slow down system.
"#{}" is
call string interpolation. If you write a set variable inside the
brackets "{}" then it will output whatever the variable was
set to when using either the "print" or "puts"
command.
- Input: my_name
= "David"
print "#{my_name}"
Output: David
Project
All the following inputs will give you the same output.
INPUTS
OUTPUT
/end of first project =)
No comments:
Post a Comment