#WDI Week 1 Notes
##Monday
###Command Line
top - table of processes (q to quit or ctrl + c)
pwd - print working directory
cd - change directory eg cd /users or cd /demo
ls - list of files
ls -l - long list of files
cd / - takes you back to the root folder
cd - takes you back to your home directory
mkdir Projects - creates a new projects folder
open . - opens the current directory or folder
open .. - opens the previous directory
cd .. - takes me up one level, to the previous directory
cd - (cd minus) takes you back to the previous directory that you were in
you can type some of the file name and then hit tab
ls -la - give me the long list of all files including hidden files
touch README - creates a file called README
open -a "Sublime Text 2" - (open application) can also do this with "Google Chome", etc
open -a "Sublime Text 2" README - (opens readme file with sublime text 2)
cat README - shows you what is in the file on the screen
To change a setting: open -a "Sublime Text 2" ~/.bash_profile
In the .bash_profile file: alias subl="open -a 'Sublime Text 2'"
subl in your terminal will now open sublime
subl . - opens the current directory in sublime
subl filename - opens that file if it's in the directory that you are in
cp README README.backup - creates a copy of a file, copy, file to copy, new file name
mv README.backup .. - moves readme up one level
mv README.backup README.accident - renames README.backup to README.accident
rm REMOVES the file
ls c* - shows all files that begin with c
ls -l *txt - shows long list of all files with.txt
^ the up arrow allows you to skip through previous commands
Know the 'which' command
ruby --help - prints a list of arguments you can pass in
man ls - brings up the manual listing for the ls command
###GitHub GIST
Some paragraph of text.
- list 1
- list 2
- list 3
Some paragraph of text with a link.
Here is a link: http://www.abc.net.au/news/
Some paragraph of text.
- list 1
- list 2
- list 3
Some paragraph of text with an image.
Today we learned the cd
command and the pwd
command.
puts"Aliens"
gets.chomp
###Ruby Basics
#Here are some basic ruby examples
puts "Hello world from Ruby"
puts 5 * 13
#TYPES
#Integers:
1
5
-1000
#Decimals or floating points:
0.67
157.2
-0.45
#Strings:
"Hello world"
'That doesn\'t sound "iffy" to me.'
"I can't even."
puts "What is your first name?"
first_name = gets.chomp.capitalize
puts "What is your surname?"
last_name = gets.chomp.capitalize
puts "Your full name is #{first_name} #{last_name}."
puts "What is your suburb?"
suburb = gets.chomp.capitalize
puts "You live in #{suburb}"
#Booleans:
true
false
#Variables:
age = 27
age = age + 1
age += 1
snake_case = "local variable"
# ClassNamesUseCamelCase
ANSWER_TO_EVERYTHIG = "something that's never going to change"
2 * 3
1 - 5
4 / 2
5 / 5
5 % 2
5 ** 5 #five to the power of five
'grape' + 'fruit'
drink = 'scotch'
"My favourite drink is #{drink}" #interpolation
"My favourite drink is " + drink
"The sum is #{4 + 18}"
#Comparisons:
>
<
>=
<=
!=
# you can run the file basics.rb in the terminal by using ruby basics.rb
# you can also run irb in your console
# irb stands for interactive ruby
# it then issues a prompt and you can experiment with ruby directly in the console eg 13 * 5
###Homework
https://gist.github.com/wofockham/6f4980cfc1ac4c9752d2
https://www.youtube.com/watch?v=ZDR433b0HJY
##Tuesday
###Git Intro
Run git status from whichever directory you are in, tells you which files are tracked or untracked
diff --git will tell you what changes you have made
git add 00-intro/ (Adds all files within the folder that have had changes made)
git add 00-intro/file.txt (Adds a specific file within a folder)
Re-run git status and it will tell you which chages are to be committed
Use git reset HEAD to unstage (the opposite of git add)
git commit -m "My informative message about what changes were made goes here."
re run git status and it says your branch is ahead of origin master by one committ
origin is what's on the github server
So the next step is to push changes to GitHub
git push origin master
- in the terminal move to the folder you want to be in
- copy the clone url from soneones git hub repo
- then type git clone https://github.com/wofockham/wdi-8.git
cd into the new folder and type git pull
it will either pull down the latest version or tell you if the folder is already up to date
-
first thing you should do is git status - if it says this is not a git repository, then you are good to create a new repository! you just want to make sure you are no already in a repository
-
git init
-
git status
-
git add octocat.txt
-
git status, will now show there is a new file octocat.txt
-
git commit -m "Add cute octocat story"
-
git add '*.txt' adds anything with .txt at the end
-
git commit -m "Add all the octocat txt files."
-
git remote add origin "url" - this links the local repository to the github repo
-
git push -u origin master - now all the work done locally is pushed up to my github repo. they are currently in sync.
-
git pull origin master - pulls down the master from the github server
-
git diff HEAD - tells me the difference between my latest version and the version that's on github
-
to revert a file back to its previous version.. git checkout -- octocat.txt (this takes you back to the last version of the file that has been added, not committed)
checkout lets you go back to a previous version reset allows you to remove something from staging
Creating, merging and deleting a branch:
git branch clean_up
git checkout clean_up
git rm '*.txt'
git commit -m "Remove all the cats"
git checkout master - goes back to the master branch
git merge clean_up - merges all changes you made in the clean_up branch into the master
git branch -d clean_up - deletes the other branch, now that you have two the same, clean_up and master
git push (no need to repeat git push -u origin master, because the -u means it will remember that command)
###Ruby flow
####Conditionals
#boring examples
if true
puts "It is true"
end
if false
puts "It is false"
end
#mathematical consistency
if (2+2 == 4)
puts "Maths appears to be correct"
end
if (2+2 == 5)
puts "Maths is broken"
end
if (3+3 == 9)
puts "Maths is misbehaving"
else
puts "Maths is a-okay"
end
--
name = "Craigsy"
if name == "Craigsy"
puts "Hey there buddy"
else
puts "Hi stranger"
end
--
password = 'swordfish'
unless password == 'swordfish'
puts "You don't know the password"
else
puts "Welcome"
end
puts "You don't know the password" unless password == 'swordfish'
####Functions
timber_length = 12
timber_width = 18
def area (length, width)
length*width
end
puts "The area is #{area(timber_length, timber_width)}"
--
def volume (length, width, height)
length * width * height
end
puts "The volume is #{volume(11, 12, 13)}"
--
def square(n)
n * n
end
puts "The square is #{square(7)}"
--
def cube(n)
n * n * n
end
puts "The cube is #{cube(3)}"
--
def name_tag(first, last, gender, age)
if gender == 'f'
if age < 19
"Miss #{first} #{last}"
else
"Ms. #{first} #{last}"
end
else
"Mr #{first} #{last}"
end
end
puts name_tag('Groucho','Marx', 'm', 30)
puts name_tag('Amy', 'Simmons', 'f', 27)
--
def italic(text)
"<i>" + text + "</i>"
end
puts italic("Marx Brothers")
def bold(text)
"<strong>" + text + "</strong>"
end
puts bold("Duck soup")
###Homework: Lab Calculator
Instructions: https://gist.github.com/wofockham/2752aa06121df7f3024c
while @choice != "q"
puts "Welcome to Crappy Calc"
puts "Available functions:"
puts "1. Addition"
puts "2. Subtraction"
puts "3. Multiply"
puts "4. Divide"
puts "5. Square root"
puts "6. Exponent"
puts "Q. Quit"
print "Please enter your selection: "
@choice = gets.chomp.downcase
case @choice
when "1"
print "Enter the first number: "
x = gets.to_i
print "Enter the number you want to add: "
y = gets.to_i
result = x + y
puts "#{x} + #{y} = #{result}"
when "2"
print "Enter the first number: "
x = gets.to_i
print "Enter the number you want to subtract: "
y = gets.to_i
result = x - y
puts "#{x} - #{y} = #{result}"
when "3"
print "Enter the first number: "
x = gets.to_i
print "Enter the number you want to multiply by: "
y = gets.to_i
result = x * y
puts "#{x} * #{y} = #{result}"
when "4"
print "Enter the first number: "
x = gets.to_i
print "Enter the number you want to divide by: "
y = gets.to_i
unless x % y > 0
result = x / y
else
result = x.to_f / y.to_f
end
puts "#{x} / #{y} = #{result}"
when "5"
print "Enter the number you would like the square root of: "
x = gets.to_i
result = Math.sqrt(x)
puts "The square root of #{x} = #{result}"
when "6"
print "Enter the base number: "
x = gets.to_i
print "To the power of: "
y = gets.to_i
result = x ** y
puts "#{x} ^ #{y} = #{result}"
when "q"
puts "Thanks for using Crappy Calc!"
else
puts "That's not a valid function. Please make another choice."
end
end
##Wednesday
###Arrays
b[2] #access
b[2] = 'something' #assignment
b[1].length #testing the length of a specific element in an array
b << 'something' #adding to an array
.push #adds a new element to the end of the array
.pop #removes the last element from the array
.shift #removes the first element from the array
.unshift #adds a new element to the start of the array
15..20 #gives you back a range
(15..20).to_a #gives you an array of all the numbers from 15 to 20
(15...20).to_a #gives you an array of all the numbers from 15 up to but not including 20
In Ruby you can also add and subtract arrays:
[1, 2, 3] + [50, 100]
=> [1, 2, 3, 50, 100]
[1, 2, 2, 9 , 1001] - [7, 1]
=> [2, 2, 9, 1001]
[1, 2, 3] & [3, 50, 100]
=> [3]
sisters = ["amy", "gemma", "lauren", "emma", "cassie"]
puts sisters[0] #first sis
puts sisters[4] #last sis
puts sisters.last #also the last sis
puts sisters[-1] #also the last sis
puts "shift"
chocolate_eater = sisters.shift
p sisters
puts "unshift"
sisters.unshift chocolate_eater
p sisters
puts '.delete_at: deleting gemma'
sisters.delete_at 1 #vs sisters[1] = nil
p sisters
numbers = (1..100).to_a
cards = ['Ace of spades','Two of clubs', 'Queen of hearts', 'Four of diamonds']
p cards.shuffle
p cards.shuffle
#shuffles the entire deck
puts '.sample'
p cards.sample #same as cards.shuffle.first (shuffling them randomly then taking the first card)
p cards.sample 2
#gives you a random sample card/s
puts '.uniq'
p [1, 1, 1, 2, 7].uniq
#gives all the unique elements in the array
---
#to loop through an array
bros = %w{ groucho harpo chico }
#the way you would do it in lots of other programming languages
counter = 0
while counter < bros.length
puts bros[counter] + " Marx"
counter += 1
end
#the way you would do it in ruby
bros.each do |name|
print name + " Marx"
end
Days of The Week task
https://gist.github.com/wofockham/64bc0aa2857797dc4e57
# 1. Create an array of the days of the week
# Create a variable named days_of_the_week as an array of the following:
# Monday
# Tuesday
# Wednesday
# Thursday
# Friday
# Saturday
# Sunday
days_of_the_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
p days_of_the_week
# For Ex.1 you can also do this:
days_of_the_week = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday"
days_of_the_week.split(' ')
# This is even better:
days_of_the_week = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}
---
# 2. My calendar says the first day is Sunday...
# Remove Sunday from the last postion and move it to the first position. Use array methods.
days_of_the_week.pop
p days_of_the_week
days_of_the_week.unshift 'Sunday'
p days_of_the_week
# For Ex.2 you can also do this:
days_of_the_week.rotate -1
#And this:
days_of_the_week.unshift days_of_the_week.pop
#pops off the last element and unshifts it to the front of the array
---
# 3. Create a new array of the days of the week:
# The first inner array should be the weekdays
# The second inner array should be the weekend days
days_of_the_week = [["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], ["Saturday", "Sunday", "Another"]]
p days_of_the_week
# Other ways of doing Ex.3:
new_days = days_of_the_week[1,5]
#give me five eleements of the array starting from position 1
new_days = [ days_of_the_week[1..5], [days_of_the_week.last, days_of_the_week.first] ]
#give me five elements of the array starting from position 1 up to and including 5
---
# 4. Remove either the weekdays or the weekends
# Your choice...
days_of_the_week.delete_at 0
p days_of_the_week
# new_days.delete_at 0
---
# 5. Sort the remaining days alphabetically
days_of_the_week.flatten!.sort!
p days_of_the_week
# new_days.flatten.sort
###Hashes
Hashes contain associative data.
hash_name.keys #returns the hash keys
hash_name.values #returns the hash values
You shouldn't really use hash_name.first on a hash, as you would on an array, because hashes aren't ordered like arrays. Order doesn't matter in hashes.
Hashes task:
https://gist.github.com/wofockham/50a52e9399075709fe87
# A. Given the following data structure:
a = ["Anil", "Erik", "Jonathan"]
# How would you return the string "Erik"?
a[1]
# How would you add your name to the array?
a << "Amy"
# or
a.push 'Amy'
# B. Given the following data structure:
h = {0 => "Zero", 1 => "One", :two => "Two", "two" => 2}
# How would you return the string "One"?
h[1]
# How would you return the string "Two"?
h[:two]
# How would you return the number 2?
h["two"]
# How would you add {3 => "Three"} to the hash?
h[3] = "Three"
# How would you add {:four => 4} to the hash?
h[:four] = 4
# C. Given the following data structure:
is = {true => "It's true!", false => "It's false"}
# What is the return value of is[2 + 2 == 4]?
"It's true"
# What is the return value of is["Erik" == "Jonathan"]?
"It's false"
# What is the return value of is[9 > 10]?
"It's false"
#What is the return value of is[0]?
nil
#What is the return value of is["Erik"]?
nil
# D. Given the following data structure:
users = {
"Jonathan" => {
:twitter => "tronathan",
:favorite_numbers => [12, 42, 75],
},
"Erik" => {
:twitter => "sferik",
:favorite_numbers => [8, 12, 24],
},
"Anil" => {
:twitter => "bridgpal",
:favorite_numbers => [12, 14, 85],
},
}
# How would you access Jonathan's Twitter handle (i.e. the string "tronathan")?
users["Jonathan"][:twitter]
# How would you add the number 7 to Erik's favorite numbers?
users['Erik'][:favorite_numbers] << 7
# How would you add yourself to the users hash?
# users.keys << "Amy"
users["Amy"] = { :twitter=>"amesimmons", :favorite_numbers=>[2,22,24] }
# How would you return the array of Erik's favorite numbers?
users['Erik'][:favorite_numbers]
# How would you return the smallest of Erik's favorite numbers?
users['Erik'][:favorite_numbers].min
# How would you return an array of Anil's favorite numbers that are also even?
users['Anil'][:favorite_numbers].select { |num| num.even? }
#this says go and get anil's favourite numbers and select the ones which are even
# How would you return an array of the favorite numbers common to all users?
users['Erik'][:favorite_numbers] & users['Anil'][:favorite_numbers] & users['Jonathan'][:favorite_numbers]
*Note: But what if i added another user to the hash? It would be better to go through each of the users.
# How would you return an array containing all users' favorite numbers, sorted, and excluding duplicates?
all_nums = users['Erik'][:favorite_numbers] + users['Anil'][:favorite_numbers] + users['Jonathan'][:favorite_numbers]
all_nums.sort.uniq
# or wrap it in parenthesis
(users['Erik'][:favorite_numbers] + users['Anil'][:favorite_numbers] + users['Jonathan'][:favorite_numbers]
all_nums).sort.uniq
###Symbols
If you had a database for a million people, and you wanted to store an address for each, the word 'address' would be identical, repeated a million times. Each word address would have its own object_id.
- the string for address is "address"
- the symbol for address is :address
You can convert strings to symbols and symbols to strings:
- "address".to_sym
- :address.to_s
When using hashes, you should almost alwasy use symbols for keys.
Eg:
instruments = {
:groucho => 'guitar',
:harpo => 'harp,
:chico => 'piano'
}
instruments[:groucho]
#To store multiple values
instruments[:groucho] = ['guitar', 'mouth harp']
instruments[:groucho][0]
instruments[:groucho][1]
##Homework: MTA
My first attempt at this killer:
https://gist.github.com/wofockham/399e315a90e04a867455
# Activity:
# Students should create a program that models a simple subway system.
# The program takes the line and stop that a user is getting on at and the line and stop that user is getting off at and prints the total number of stops for the trip.
# There are 3 subway lines:
# The N line has the following stops: Times Square, 34th, 28th, 23rd, Union Square, and 8th
# The L line has the following stops: 8th, 6th, Union Square, 3rd, and 1st
# The 6 line has the following stops: Grand Central, 33rd, 28th, 23rd, Union Square, and Astor Place.
# All 3 subway lines intersect at Union Square, but there are no other intersection points.
# For example, this means the 28th stop on the N line is different than the 28th street stop on the 6 line, so you'll have to differentiate this when you name your stops in the arrays.
# Hints:
# Consider diagraming the lines by sketching out the subway lines and their stops and intersection.
# Make subway lines are keys in a hash, while the values are an array of all the stops on each line.
# The key to the lab is to find the intersection of the lines at Union Square.
# Make sure the stops that are the same for different lines have different names (i.e. 23rd on the N and on the 6 need to be differentiated)
#creates a subway_lines hash
subway_lines = {
"N" => ["Times Square", "34th", "28th(N)", "23rd(N)", "Union Square", "8th(N)"],
"L" => ["8th(L)", "6th", "Union Square", "3rd", "1st"],
"6" => ["Grand Central", "33rd", "28th(6)", "23rd(6)", "Union Square", "Astor Place"]
}
#gets user inputs and stores them in variables
puts "Which line are you getting on at? "
puts subway_lines.keys
print '> '
line_on = gets.chomp.upcase
puts "Which stop are you getting on at?"
if line_on == "N"
puts subway_lines["N"]
elsif line_on == "L"
puts subway_lines["L"]
elsif line_on == "6"
puts subway_lines["6"]
else
puts "No such line!"
end
print '> '
stop_on = gets.chomp
puts "Which line are you getting off at?"
puts subway_lines.keys
print '> '
line_off = gets.chomp.upcase
puts "Which stop are you getting off at?"
if line_off == "N"
puts subway_lines["N"]
elsif line_off == "L"
puts subway_lines["L"]
elsif line_off == "6"
puts subway_lines["6"]
else
puts "No such line!"
end
print '> '
stop_off = gets.chomp
# def total_stops_single_line
# end
# def total_stops_line_change
# end
#executes code depending on whether the traveller is staying on the same line
if line_on == line_off && subway_lines[line_on].index(stop_on) < subway_lines[line_on].index("Union Square") && subway_lines[line_off].index(stop_off) > subway_lines[line_off].index("Union Square")
index_1 = subway_lines[line_on].index(stop_on)
index_2 = subway_lines[line_off].index(stop_off)
stations = subway_lines[line_on][index_1..index_2]
stations.shift
total_stops = stations.length
puts "Your destination is #{total_stops} stops away."
elsif line_on == line_off && subway_lines[line_on].index(stop_on) > subway_lines[line_on].index("Union Square") && subway_lines[line_off].index(stop_off) < subway_lines[line_off].index("Union Square")
index_1 = subway_lines[line_off].index(stop_off)
index_2 = subway_lines[line_on].index(stop_on)
stations = subway_lines[line_on][index_1..index_2]
stations.shift
total_stops = stations.length
puts "Your destination is #{total_stops} stops away."
#executes code depending on whether the traveller is changing lines, and:
#whether they get on at a stop before union square and get get off at a stop after it on another line
elsif line_on != line_off && subway_lines[line_on].index(stop_on) < subway_lines[line_on].index("Union Square") && subway_lines[line_off].index(stop_off) > subway_lines[line_off].index("Union Square")
index_1 = subway_lines[line_on].index(stop_on)
index_2 = subway_lines[line_on].index("Union Square")
index_3 = subway_lines[line_off].index("Union Square")
index_4 = subway_lines[line_off].index(stop_off)
stops_on_first_line = subway_lines[line_on][index_1..index_2]
stops_on_first_line.shift
stops_on_second_line = subway_lines[line_off][index_3..index_4]
stops_on_second_line.shift
total_stops = stops_on_first_line.length + stops_on_second_line.length
puts "Your destination is #{total_stops} stops away. You'll need to change lines at Union Square."
#whether they get on at a stop before union square and get get off at a stop before it on another line
elsif line_on != line_off && subway_lines[line_on].index(stop_on) < subway_lines[line_on].index("Union Square") && subway_lines[line_off].index(stop_off) < subway_lines[line_off].index("Union Square")
index_1 = subway_lines[line_on].index(stop_on)
index_2 = subway_lines[line_on].index("Union Square")
index_3 = subway_lines[line_off].index(stop_off)
index_4 = subway_lines[line_off].index("Union Square")
stops_on_first_line = subway_lines[line_on][index_1..index_2]
stops_on_first_line.shift
stops_on_second_line = subway_lines[line_off][index_3..index_4]
stops_on_second_line.shift
total_stops = stops_on_first_line.length + stops_on_second_line.length
puts "Your destination is #{total_stops} stops away. You'll need to change lines at Union Square."
#whether they get on at a stop after union square and get get off at a stop before it on another line
elsif line_on != line_off && subway_lines[line_on].index(stop_on) > subway_lines[line_on].index("Union Square") && subway_lines[line_off].index(stop_off) < subway_lines[line_off].index("Union Square")
index_1 = subway_lines[line_on].index("Union Square")
index_2 = subway_lines[line_on].index(stop_on)
index_3 = subway_lines[line_off].index(stop_off)
index_4 = subway_lines[line_off].index("Union Square")
stops_on_first_line = subway_lines[line_on][index_1..index_2]
stops_on_first_line.shift
stops_on_second_line = subway_lines[line_off][index_3..index_4]
stops_on_second_line.shift
total_stops = stops_on_first_line.length + stops_on_second_line.length
puts "Your destination is #{total_stops} stops away. You'll need to change lines at Union Square."
#whether they get on at a stop after union square and get get off at a stop after it on another line
elsif line_on != line_off && subway_lines[line_on].index(stop_on) > subway_lines[line_on].index("Union Square") && subway_lines[line_off].index(stop_off) > subway_lines[line_off].index("Union Square")
index_1 = subway_lines[line_on].index("Union Square")
index_2 = subway_lines[line_on].index(stop_on)
index_3 = subway_lines[line_off].index("Union Square")
index_4 = subway_lines[line_off].index(stop_off)
stops_on_first_line = subway_lines[line_on][index_1..index_2]
stops_on_first_line.shift
stops_on_second_line = subway_lines[line_off][index_3..index_4]
stops_on_second_line.shift
total_stops = stops_on_first_line.length + stops_on_second_line.length
puts "Your destination is #{total_stops} stops away. You'll need to change lines at Union Square."
elsif stop_on == stop_off
puts "You're already there!"
end
##Thursday
###Enumerables
###Classes + Objects
Why we would want to use objects and classes:
- To help structure the code
- More like the real world than arrays and hashes
Using @ on a variable is like putting a hat on a variable to show that it's important, and to say hang on to this person's age, I want to remember the age for later.
Writing the function def age=(age) allows you to get a person's age like this:
craig.age=(25)
craig.age = 30
Note: if you don't define a getter and a setter, like for the @music_preference variable below, it means you don't have access to the instance variable outside the function
CODE BEFORE ATTR_ACCESSOR:
class Person
#def initialize creates a special magic method called initialize. Whenever I call a new Person, it will trigger the initialize function and allow me to pass through those variables
def initialize(age, gender, name)
puts "Look at me I am initializing"
@age = age
@gender = gender
@name = name
@music_preference = "pop"
end
#this is the age setter
def age=(age)
@age = age
end
#this is the age getter
def age
@age
end
#this is the gender setter
def gender=(gender)
@gender = gender
end
#this is the gender getter
def gender
@gender
end
#this is the name setter
def name=(name)
@name = name
end
#this is the name getter
def name
@name
end
end
HOW ATTR_ACCESSOR CHANGES THE CODE:
attr_accessor :age
is the same as
#this is the age setter
def age=(age)
@age = age
end
#this is the age getter
def age
@age
end
... But because this is repeated so often in Ruby, they created attr_accessor. This code does the same as the long chunk above:
class Person
attr_accessor :age, :gender, :name #creates getter and setter methods for our instance variables
def initialize(age, gender, name)
puts "Look at me I am initializing"
@age = age
@gender = gender
@name = name
@music_preference = "pop"
end
end
###Lab: Rental
My attempt:
https://github.com/amysimmons/wdi8_homework/tree/master/amy/rental
##Friday
###Review
####Scope
cool = "Beans"
def dinner_plans()
puts cool
end
dinner_plans()
This will return the folloowing error msg: undefined local variable or method `cool' for main:Object
Rewrite like this:
def dinner_plans(cuisine)
puts cuisine
end
dinner_plans("Beans")
def blah()
my_var = "my_var has been defined"
end
puts my_var
The above code will give this error msg: undefined local variable or method `my_var'
Rewrite like this:
def blah()
my_var = "my_var has been defined"
puts my_var
end
blah()
Methods can call other methods:
def first_name()
return("Otto")
end
def last_name()
return("Mation")
end
def full_name()
first_name() + " " + last_name()
end
puts full_name()
Note: Variables have scope so you can't acces them outside a function. But that doesn't apply to functions. Functions can access other functions from outside themselves.
Each v map loops:
The longer way:
doubles = []
[2, 4, 6, 8].each do |n|
doubles << n*2
end
The shorter way:
[2, 4, 6, 8].map do |number|
number ** 2
end
The map() method iterates though every element of an array and returns a new array. In this example, the new array contains the squared value of the old array.
Hashes:
This is saying, go into this hash ahd get me this key:
warty_newt = { "type" => "Amphibian", "diet" => "Carnivore", "life_span" => "25 years" }
warty_newt["type"]
This is saying, go into this hash and fetch me this key:
warty_newt = { "type" => "Amphibian", "diet" => "Carnivore", "life_span" => "25 years" }
warty_newt.fetch("type")
If you are looking for a key that doesn't exist, fetch will throw an error, rather than return nil. Thats the only difference between ["type"] and .fetch("type") in the above two examples.
Returning keys and values:
Return keys:
snowy_owl = { "type"=>"Bird", "diet"=>"Carnivore", "life_span"=>"10 years" }
snowy_owl.keys()
["type", "diet", "life_span"]
Return values:
snowy_owl = { "type"=>"Bird", "diet"=>"Carnivore", "life_span"=>"10 years" }
snowy_owl.values()
["Bird", "Carnivore", "10 years"]
Give me back the type key only:
snowy_owl = {
"type"=>"Bird",
"diet"=>"Carnivore",
"life_span"=>"10 years"
}
snowy_owl.select do |key, value|
key == "type"
end
{"type"=>"Bird"}
Give me back the type and diet keys:
snowy_owl = {
"type"=>"Bird",
"diet"=>"Carnivore",
"life_span"=>"10 years"
}
snowy_owl.select do |key, value|
key == "type" || key == "diet"
end
{"type"=>"Bird", "diet"=>"Carnivore"}
###Happitails
Homework task:
https://gist.github.com/wofockham/1cbb5fb3fcf592a42431
My attempt:
https://github.com/amysimmons/wdi8_homework/tree/master/amy/Happitails