Skip to content

Instantly share code, notes, and snippets.

@NimaBoscarino
Created April 15, 2019 17:55
Show Gist options
  • Save NimaBoscarino/8b072892a4fb8053f5c0cd6b2ceffd7f to your computer and use it in GitHub Desktop.
Save NimaBoscarino/8b072892a4fb8053f5c0cd6b2ceffd7f to your computer and use it in GitHub Desktop.
dog = 'Spot'
puts dog
p dog
print dog
print dog
print dog
print dog
p "There are many ways to print things! What are the differences?"
# Methods (functions) are defined with def
def sayHello
# return 'goodbye' # you can OPTIONALLY write the return
puts 'what up its ya boi'
'hello' # ruby has an implicit return statement!
# The last line of code that gets executed in your method is the return statement.
end
puts sayHello # Any time that you write the name of the method, you are invoking it.
# If statements can work the same as they do in JavaScript...
# OR you can use funky things like "unless"! (Like saying "if not...")
def sayNumber number
unless false
puts 'boo'
else
puts number
end
end
sayNumber 1337
# Unless!
puts "3 is bigger than 1" unless 3 < 1
# nil insteal of null/undefined
a = nil
# more conditionals
if a
puts 'first'
elsif 3 < 2 # Ruby says elsif instead of "else if"
puts 'second'
else
puts 'third'
end
# ternary is the same!
a = true
a ? 'a is truthy' : 'a is falsy'
# Reassigning variables
variable = 1
variable = 2
# Constants in Ruby are done with the first letter being a capital
ConstantThing = 'kanye'
ConstantThing = 'drake' # error!
# Loops
# You can do for.. loops and while loops, but the loop we looked at was an .each loop
dogs = ['spot', 'bob', 'frida']
dogs.each do |x|
puts x
end
# This looks funky because we're using some do... thing. This is called a block!
# A block is essentially a callback in Ruby.
# We also looked at things like <NUMBER>.times
1000.times do # Yup, Ruby lets you do this!
puts 'YEEZY!'
end
# Whoops, 1001 times. This is a worse version of the avove
index = 0
until index > 1000
puts index
puts 'YEEZY!'
index = index + 1
end
# Symbols
# Ruby has these things called "Symbols". They're ESSENTIALLY strings
someSymbol = :haha
# Hashes! Ruby's JS-like-objects
# Symbols are useful when we're working with hashes, Ruby's version of objects.
# The key to this hash is a SYMBOL.
person = {age: 60, name: 'Simone Simonson'}
person[:age]
# Same here! This is slightly different syntax for the example above.
person = {:age => 60, :name => 'Simone Simonson'}
person[:age]
# Be careful about this! In this case, the key is a string.
person = {"age" => 60, "name" => 'Simone Simonson'}
person["age"]
# Lambdas - not in scope of the curriculum, but interesting!
# Someone had an interesting question about Lambdas. They are like Ruby's verion of anonymous functions.
doThing = lambda { |num| puts num }
# const doThing = function (num) { console.log(num) }
# const doThing = num => console.log(num)
[1, 2, 3].each &doThing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment