Skip to content

Instantly share code, notes, and snippets.

@therod
Last active January 11, 2021 15:10
Show Gist options
  • Save therod/d2e49aad43e28667b39521aa411d8925 to your computer and use it in GitHub Desktop.
Save therod/d2e49aad43e28667b39521aa411d8925 to your computer and use it in GitHub Desktop.

Ruby Cheatsheet

Basic Math Operations

5.4 - 2.2 # Subtraction
4 * 72 # Multiplication
7 / 3.5 # Division
3 ** 7  # Exponentiation

Comparing Values

4 < 6 # true
4 > 6 # false
2 + 2 == 6 # false
2 + 2 == 4 # true
3.0 == 3 # true

Printing on Screen

# Puts adds a line break at the end
puts "Hello brave new world"
puts "I like Ruby!"

# Print does not add line break
print "Hello "
print "world!"

String interpolation

puts "The Answer is #{6 * 7}." # Result: The answer is 42.

Variables

answer = "42"
puts "The answer is #{answer}." # Result: The answer is 42.

big_number = 223
small_number = 7
puts big_number + small_number # Result: 230

User Input

print "Please enter your name: "
name = gets.chomp
puts "Nice to meet you, #{name}!

Everything is an object

"Hello".upcase # Result: HELLO
"Hello".reverse # Result: olleH
"hEllO".downcase # Result: hello
"Hi there".length # Result: 8
43.even? # Result: false
3.next # Result: 4
"Hello".class # Result: String
43.class # Result: Integer
2.5.class # Result: Float
true.class # TrueClass

if Conditional

if 1 < 2
  puts “one smaller than two”
elsif 1 > 2 # *careful not to mistake with else if. In ruby you write elsif*
  puts “elsif”
else
  puts “false”
end

puts "be printed" if true
puts 3 > 4 ? "if true" : "else" # else will be putted

Loop iterator

i = 0
loop do
  i += 1
  print "I'm currently number #{i} # a way to have ruby code in a string
  break if i > 5
end

Arrays

breakfast = ["Bacon", "Cheese", "Eggs"]
puts breakfast
breakfast = ["Bacon", "Cheese", "Eggs"]
puts breakfast[1] # Result:  Cheese
breakfast = ["Bacon", "Cheese", "Eggs"]
breakfast[1] = "Sardines"
puts breakfast 
# Result: 
# Bacon 
# Sardines 
# Eggs

Special Character Table

DE Layout

DE Layout

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment