Codecademy Cheatsheet
Everything in Ruby is an Object
'puts' and 'print'
The print command just takes whatever you give it and prints it to the screen. puts (for “put string”) is slightly different: it adds a new (blank) line after the thing you want it to print. You use them like this:
puts "What's up?"
print "Oxnard Montalvo"
No parentheses or semicolons needed!
The '.length' Method
"I love espresso".length
# ==> 15
The '.reverse' Method
"Eric".reverse
will result in
"cirE"
'.upcase' & '.downcase'
puts "Aizat".upcase
puts "Aizat".downcase
Multi-Line Comments
=begin
This is for when
you have a lot of comments to write!
=end
Strings and String Methods
In Ruby, you can do this two ways: each method call on a separate line, or you can chain them together, like this:
name.method1.method2.method3
name = "Jamie"
puts name.downcase.reverse.upcase
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.)
variable_name = gets.chomp
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
Top comments (0)