1
0
Fork 0

chore: commit previous exercises

main
James Spencer 2023-09-30 14:20:59 +01:00
commit 97851a0e79
Signed by: james
SSH Key Fingerprint: SHA256:7tOVvkg3eVqn4GbEInHoSkEG96Cvqgvwx+VHUD9begc
47 changed files with 1222 additions and 0 deletions

10
.rubocop.yml Normal file
View File

@ -0,0 +1,10 @@
require:
- standard
- standard-custom
- standard-performance
- rubocop-performance
inherit_gem:
standard: config/base.yml
standard-custom: config/base.yml
standard-performance: config/base.yml

17
.solargraph.yml Normal file
View File

@ -0,0 +1,17 @@
---
include:
- "**/*.rb"
exclude:
- spec/**/*
- test/**/*
- vendor/**/*
- ".bundle/**/*"
require: []
domains: []
reporters:
- rubocop
- require_not_found
- typecheck
require_paths: []
plugins: []
max_files: 5000

7
Gemfile Normal file
View File

@ -0,0 +1,7 @@
source "https://rubygems.org"
gem "solargraph", group: :development
gem "rdoc", "~> 6.5"
gem "rubocop", "~> 1.56"

80
Gemfile.lock Normal file
View File

@ -0,0 +1,80 @@
GEM
remote: https://rubygems.org/
specs:
ast (2.4.2)
backport (1.2.0)
base64 (0.1.1)
benchmark (0.2.1)
diff-lcs (1.5.0)
e2mmap (0.1.0)
jaro_winkler (1.5.6)
json (2.6.3)
kramdown (2.4.0)
rexml
kramdown-parser-gfm (1.1.0)
kramdown (~> 2.0)
language_server-protocol (3.17.0.3)
nokogiri (1.15.4-arm64-darwin)
racc (~> 1.4)
parallel (1.23.0)
parser (3.2.2.3)
ast (~> 2.4.1)
racc
psych (5.1.0)
stringio
racc (1.7.1)
rainbow (3.1.1)
rbs (2.8.4)
rdoc (6.5.0)
psych (>= 4.0.0)
regexp_parser (2.8.1)
reverse_markdown (2.1.1)
nokogiri
rexml (3.2.6)
rubocop (1.56.3)
base64 (~> 0.1.1)
json (~> 2.3)
language_server-protocol (>= 3.17.0)
parallel (~> 1.10)
parser (>= 3.2.2.3)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.8, < 3.0)
rexml (>= 3.2.5, < 4.0)
rubocop-ast (>= 1.28.1, < 2.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 2.4.0, < 3.0)
rubocop-ast (1.29.0)
parser (>= 3.2.1.0)
ruby-progressbar (1.13.0)
solargraph (0.49.0)
backport (~> 1.2)
benchmark
bundler (~> 2.0)
diff-lcs (~> 1.4)
e2mmap
jaro_winkler (~> 1.5)
kramdown (~> 2.3)
kramdown-parser-gfm (~> 1.1)
parser (~> 3.0)
rbs (~> 2.0)
reverse_markdown (~> 2.0)
rubocop (~> 1.38)
thor (~> 1.0)
tilt (~> 2.0)
yard (~> 0.9, >= 0.9.24)
stringio (3.0.8)
thor (1.2.2)
tilt (2.3.0)
unicode-display_width (2.4.2)
yard (0.9.34)
PLATFORMS
arm64-darwin-22
DEPENDENCIES
rdoc (~> 6.5)
rubocop (~> 1.56)
solargraph
BUNDLED WITH
2.4.10

9
Rakefile Normal file
View File

@ -0,0 +1,9 @@
require "rdoc/task"
task default: [:rdoc]
Rake::RDocTask.new do |rdoc|
rdoc.rdoc_dir = "rdoc"
rdoc.title = "rdoc"
rdoc.options << "--line-numbers" << "--inline-source"
rdoc.rdoc_files.include("**/*.rb")
end

8
exercises/ex1.rb Normal file
View File

@ -0,0 +1,8 @@
# puts "Hello World!"
# puts "Hello Again"
# puts "I like typing this."
# puts "This is fun."
# puts "Yay! Printing."
# puts "I'd much rather you 'not'."
# puts 'I "said" do not touch this.'
puts "Esther fucked my brains out"

19
exercises/ex10.rb Normal file
View File

@ -0,0 +1,19 @@
puts "I am 6'2\" tall." # escape double-quote inside string
puts 'I am 6\'2" tall.' # escape single-quote inside string
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = "
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"
puts tabby_cat
puts persian_cat
puts backslash_cat
puts fat_cat
puts "\x10 bell"

8
exercises/ex11.rb Normal file
View File

@ -0,0 +1,8 @@
print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.chomp
print "How much do you weigh? "
weight = gets.chomp
puts "So, you're #{age} years old, #{height} tall and #{weight} heavy."

17
exercises/ex12.rb Normal file
View File

@ -0,0 +1,17 @@
print "Give me a number: "
number = gets.chomp.to_i
bigger = number * 100
puts "A bigger number is #{bigger}."
print "Give me another number: "
another = gets.chomp
number = another.to_i
smaller = number / 100
puts "A smaller number is #{smaller}."
print "Give me some money! $"
money = gets.chomp.to_f
puts "You can have 10% back: $#{(money / 100 * 10).round(2)}"

9
exercises/ex13.rb Normal file
View File

@ -0,0 +1,9 @@
first, second, third = ARGV
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
puts "Do a thing"
thing = $stdin.gets.chomp
puts thing

22
exercises/ex14.rb Normal file
View File

@ -0,0 +1,22 @@
user_name = ARGV.first # gets the first argument
prompt = "> "
puts "Hi #{user_name}"
puts "I'd like to ask you a few questions."
puts "Do you like me #{user_name}? "
puts prompt
likes = $stdin.gets.chomp
puts "Where do you live #{user_name}? "
puts prompt
lives = $stdin.gets.chomp
# a comma for puts is like using it twice
puts "What kind of computer do you have? ", prompt
computer = $stdin.gets.chomp
puts "
Alright, so you said #{likes} about liking me.
You live in #{lives}. Not sure where that is.
And you have a #{computer} computer. Nice.
"

16
exercises/ex15/ex15.rb Normal file
View File

@ -0,0 +1,16 @@
filename = ARGV.first
txt = open(filename)
puts "Here's your file #{filename}:"
print txt.read
print "Type the filename again: "
file_again = $stdin.gets.chomp
txt_again = open(file_again)
print txt_again.read
txt.close
txt_again.close

View File

@ -0,0 +1,3 @@
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

14
exercises/ex17/ex17.rb Normal file
View File

@ -0,0 +1,14 @@
from_file, to_file = ARGV
PAD = 5
str = "#{" " * PAD}Copying from #{from_file} to #{to_file}#{" " * PAD}"
puts "\e[48;5;139;233;253m#{" " * str.length}\e[0m"
puts "\e[48;5;139;233;253m#{str}\e[0m"
puts "\e[48;5;139;233;253m#{" " * str.length}\e[0m"
in_file = open(from_file)
indata = in_file.read
out_file = open(to_file, "w")
out_file.write(indata)
out_file.close
in_file.close

View File

@ -0,0 +1,5 @@
poo
poooooo
poooo
pooo
poooooo!!!!

View File

@ -0,0 +1,5 @@
poo
poooooo
poooo
pooo
poooooo!!!!

25
exercises/ex18.rb Normal file
View File

@ -0,0 +1,25 @@
# this one is like your scripts with ARGV
def print_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2)
puts "arg1: #{arg1}, arg2: #{arg2}"
end
# this just takes one argument
def print_one(arg1)
puts "arg1: #{arg1}"
end
# this one takes no arguments
def print_none
puts "I got nothin'."
end
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none

21
exercises/ex19.rb Normal file
View File

@ -0,0 +1,21 @@
def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheeses!"
puts "You have #{boxes_of_crackers} boxes of crackers!"
puts "Man that's enough for a party!"
puts "Get a blanket.\n"
end
puts "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
puts "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
puts "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
puts "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

9
exercises/ex2.rb Normal file
View File

@ -0,0 +1,9 @@
# A comment, this is so you can read your program later.
# Anything after the # is ignored by ruby.
puts "I could have code like this." # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code
# puts "This won't run."
puts "This will run."

32
exercises/ex20/ex20.rb Normal file
View File

@ -0,0 +1,32 @@
input_file = ARGV.first
def print_all(f)
puts f.read
end
def rewind(f)
f.seek(0)
end
def print_a_line(line_count, f)
puts "#{line_count}, #{f.gets.chomp}"
end
current_file = open(input_file)
puts "First let's print the whole fine:\n"
print_all(current_file)
puts "Now let's rewind, kind of like a tape."
rewind(current_file)
puts "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)

View File

@ -0,0 +1,3 @@
Meowwww in the middle of the night i crawl onto your chest and purr gently to help you sleep
Leave buried treasure in the sandbox for the toddlers prow?? ew dog you drink from the toilet, yum yum warm milk hotter pls, ouch too hot or lick the plastic bag yet i'm bored inside, let me out i'm lonely outside, let me in i can't make up my mind whether to go in or out, guess i'll just stand partway in and partway out, contemplating the universe for half an hour how dare you nudge me with your foot?!?! leap into the air in greatest offense!.
Meow all night having their mate disturbing sleeping humans hiss at vacuum cleaner oooo! dangly balls! jump swat swing flies so sweetly to the floor crash move on wash belly nap and what a cat-ass-trophy! yet cats woo and stare out the window. Poop on couch

34
exercises/ex21.rb Normal file
View File

@ -0,0 +1,34 @@
def add(a, b)
puts "Adding #{a} + #{b}"
a + b
end
def subtract(a, b)
puts "Subtracting #{a} - #{b}"
a - b
end
def multiply(a, b)
puts "Multiplying #{a} * #{b}"
a * b
end
def divide(a, b)
puts "Dividing #{a} / #{b}"
a / b
end
puts "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
puts "Age: #{age}, Height: #{height}, Weight: #{weight}, IQ: #{iq}"
# A puzzle for the extra credit, type it in anyway.
puts "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
puts "That becomes: #{what}. Can you do it by hand?"

37
exercises/ex24.rb Normal file
View File

@ -0,0 +1,37 @@
puts "Let's practice everything."
puts "You'd need to know 'bout escapes with \\ that do \n newlines and \t tabs."
# the <<END is a "heredoc". See the Student Questions
poem = <<~END
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
END
puts "-" * 10
puts poem
puts "-" * 10
five = 10 - 2 + 3 - 6
puts "This should be five: #{five}"
def secret_formula(started)
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
[jelly_beans, jars, crates]
end
start_point = 10_000
beans, jars, crates = secret_formula(start_point)
puts "With a starting point of: #{start_point}"
puts "We'd have #{beans} beans, #{jars} jars, and #{crates} crates."
start_point /= 10
puts "We can also do that this way:"
puts "We'd have %s, %d jars, and %d crates." % secret_formula(start_point)

42
exercises/ex25.rb Normal file
View File

@ -0,0 +1,42 @@
module Ex25
# This function will break up words for us.
def self.break_words(stuff)
stuff.split(" ")
end
# Sorts the words.
def self.sort_words(words)
words.sort
end
def self.print_first_word(words)
word = words.shift
puts word
end
# Prints the last word after popping it off.
def self.print_last_word(words)
word = words.pop
puts word
end
# Takes in a full sentence and returns the sorted words.
def self.sort_sentence(sentence)
words = Ex25.break_words(sentence)
Ex25.sort_words(words)
end
# Prints the first and last words of the sentence.
def self.print_first_and_last(sentence)
words = Ex25.break_words(sentence)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
end
# Sorts the words then prints the first and last one.
def self.print_first_and_last_sorted(sentence)
words = Ex25.sort_sentence(sentence)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
end
end

86
exercises/ex26.rb Normal file
View File

@ -0,0 +1,86 @@
module Ex25
# This function will break up words for us.
def self.break_words(stuff)
stuff.split(" ")
end
# Sorts the words.
def self.sort_words(words)
words.sort
end
# Prints the first word after shifting it off.
def self.print_first_word(words)
word = words.shift
puts word
end
# Prints the last word after popping it off.
def self.print_last_word(words)
word = words.pop
puts word
end
# Takes in a full sentence and returns the sorted words.
def self.sort_sentence(sentence)
words = Ex25.break_words(sentence)
Ex25.sort_words(words)
end
# Prints the first and last words of the sentence.
def self.print_first_and_last(sentence)
words = Ex25.break_words(sentence)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
end
# Sorts the words then prints the first and last one.
def self.print_first_and_last_sorted(sentence)
words = Ex25.sort_sentence(sentence)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
end
end
puts "Let's practice everything."
puts 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
poem = <<~END
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
END
puts "--------------"
puts poem
puts "--------------"
five = 10 - 2 + 3 - 6
puts "This should be five: #{five}"
def secret_formula(started)
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
[jelly_beans, jars, crates]
end
start_point = 10000
beans, jars, crates = secret_formula(start_point)
puts "With a starting point of: #{start_point}"
puts "We'd have #{beans} beans, #{jars} jars, and #{crates} crates."
sentence = "All good things come to those who wait."
words = Ex25.break_words(sentence)
sorted_words = Ex25.sort_words(words)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
Ex25.print_first_word(sorted_words)
Ex25.print_last_word(sorted_words)
Ex25.sort_sentence(sentence)
Ex25.print_first_and_last(sentence)
Ex25.print_first_and_last_sorted(sentence)

16
exercises/ex28.rb Normal file
View File

@ -0,0 +1,16 @@
true && true # true
false && true # false
1 == 1 && 2 == 1 # false # true
1 == 1 || 2 != 1 # true
true && 1 == 1 # true
false && 0 != 0 # false
true || 1 == 1 # true # false
1 != 0 && 2 == 1 # true # true # false
(true && false) # true
(1 == 1 && 0 != 1) # false
(10 == 1 || 1000 == 1000) # false
(1 != 10 || 3 == 4) # false
("testing" == "testing" && "Zed" == "Cool Guy") # true
1 == 1 && !("testing" == 1 || 1 == 0) # true
"chunky" == "bacon" && !(3 == 4 || 3 == 3) # false
3 == 3 && !("testing" == "testing" || "Ruby" == "Fun") # false

33
exercises/ex29.rb Normal file
View File

@ -0,0 +1,33 @@
people = 20
cats = 30
dogs = 15
if people < cats
puts "Too many cats! The world is doomed!"
end
if people > cats
puts "Not many cats! The world is saved!"
end
if people < dogs
puts "The world is drooled one!"
end
if people > dogs
puts "The world is dry!"
end
dogs += 5
if people >= dogs
puts "People are greater than or equal to dogs."
end
if people <= dogs
puts "People are less than or equal to dogs."
end
if people == dogs
puts "People are dogs."
end

23
exercises/ex3.rb Normal file
View File

@ -0,0 +1,23 @@
puts "I will now count my chickens:"
puts "Hens #{25 + 30 / 6}"
puts "Roosters #{100 - 25 * 3 % 4}"
puts "Now I will count the eggs:"
puts 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
puts "Is it true that 3 + 1 < 5 - 7?"
puts 3 + 2 < 5 - 7
puts "What is 3 + 2? #{3 + 2}"
puts "What is 5 - 7? #{5 - 7}"
puts "Oh, that's why it's false."
puts "How about some more."
puts "Is it greater? #{5 > -2}"
puts "Is it greater or equal? #{5 >= -2}"
puts "Is it less or equal? #{5 <= 2}"

25
exercises/ex30.rb Normal file
View File

@ -0,0 +1,25 @@
people = 30
cars = 40
trucks = 15
if cars > people
puts "We should take the cars."
elsif cars < people
puts "We should not take the cars."
else
puts "We can't decided."
end
if trucks > cars
puts "That's too many trucks."
elsif trucks < cars
puts "Maybe we could take the trucks."
else
puts "We still can't decide."
end
if people > trucks
puts "Alright, let's just take the trucks."
else
puts "Fine, let's stay home then."
end

39
exercises/ex31.rb Normal file
View File

@ -0,0 +1,39 @@
puts "You enter a dark room with two doors. Do you go through door #1 or door #2?"
print "> "
door = $stdin.gets.chomp
if door == "1"
puts "There's a giant bear here eating a cheese cake. What do you do?"
puts "1. Take the cake."
puts "2. Scream at the bear."
print "> "
bear = $stdin.gets.chomp
if bear == "1"
puts "The bear eats your face off. Good job!"
elsif bear == "2"
puts "The bear eats your legs off. Good job!"
else
puts "Well, doing %s is probably better. Bear runs away." % bear
end
elsif door == "2"
puts "You stare into the endless abyss at Cthulhus's retina."
puts "1. Blueberries."
puts "2. Yellow jacket clothespins."
puts "3. Understanding revolvers yelling melodies."
print "> "
insanity = $stdin.gets.chomp
if insanity == "1" || insanity == "2"
puts "Your body survives powered by a mind of jello. Good job!"
else
puts "The insanity rots your eyes into a pool of muck. Good job!"
end
else
puts "You stumble around and fall on a knife and die. Good job!"
end

37
exercises/ex32.rb Normal file
View File

@ -0,0 +1,37 @@
the_count = [1, 2, 3, 4, 5]
fruits = ["apples", "oranges", "pears", "apricots"]
change = [1, "pennies", 2, "dimes", 3, "quarters"]
# this first kind of for-loop goes through a list
# in a more traditional style found in other languages
# for number in the_count
# puts "This is count #{number}"
# end
the_count.each do |number|
puts "This is count #{number}"
end
# same as above, but in a more Ruby style
# this and the next one are the preferred
# way Ruby for-loops are written
fruits.each do |fruit|
puts "A fruit of type: #{fruit}"
end
# also we can go through mixed lists too
# note this is yet another style, exactly like above
# but a different syntax (way to write it).
change.each { |i| puts "I got #{i}" }
# we can also build lists, first start with an empty one
elements = []
# then use the range operator to do 0 to 5 counts
6.times do |i|
puts "adding #{i} to the list."
# pushes the i variable on the *end* of the list
elements.push(i)
end
# now we can print the out too
elements.each { |i| puts "Element was: #{i}" }

19
exercises/ex33.rb Normal file
View File

@ -0,0 +1,19 @@
def generate_numbers(max, inc)
numbers = []
(0..max - 1).step(inc) do |i|
puts "At the top i is #{i}"
numbers.push(i)
puts "Numbers now: ", numbers
puts "At the bottom i is #{i}"
end
numbers
end
numbers = generate_numbers(10, 2)
puts "The numbers: "
numbers.each do |number|
puts number
end

86
exercises/ex35.rb Normal file
View File

@ -0,0 +1,86 @@
def gold_room
puts "This room is full of gold. How much do you take?"
print "> "
choice = $stdin.gets.chomp
if /\d+/.match?(choice)
how_much = choice.to_i
else
dead("Man, learn to types a number.")
end
if how_much < 50
puts "Nice, you're not greedy, you win!"
exit(0)
else
dead("You greedy bastard!")
end
end
def bear_room
puts "There is a bear here."
puts "The bear has a bunch of honey."
puts "The fat bear is in front of another door."
puts "How are you going to move the bear?"
bear_moved = false
loop do
print ">"
choice = $stdin.gets.chomp
if choice == "take honey"
dead("The bear looks at you then slaps your face off.")
elsif choice == "taunt bear" && !bear_moved
puts "The bear has moved from the door. You can go through it now."
bear_moved = true
elsif choice == "taunt bear" && bear_moved
dead("The bear gets pissed of and chews your leg off.")
elsif choice == "open door" && bear_moved
gold_room
else
puts "I got no idea what that means."
end
end
end
def cthulhu_room
puts "Here you see the great evil Cthulhu."
puts "He, it, whatever stares at you and you go insane."
puts "Do you flee for your life or eat your head?"
print "> "
choice = $stdin.gets.chomp
if choice.include? "flee"
start
elsif choice.include? "head"
dead("Well that was tasty!")
else
cthulhu_room
end
end
def dead(why)
puts why, "Good job!"
exit(0)
end
def start
puts "You are in a dark room."
puts "There is a door to your right and left."
puts "Which one do you take?"
print "> "
choice = $stdin.gets.chomp
if choice == "left"
bear_room
elsif choice == "right"
cthulhu_room
else
dead("You stumble around the room until you starve.")
end
end
start

25
exercises/ex38.rb Normal file
View File

@ -0,0 +1,25 @@
ten_things = "Apples Oranges Crows Telephone Light Sugar"
puts "Wait there are not 10 things in that list. Let's fix that."
stuff = ten_things.split(" ")
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
# using math to make sure there's 10 items
while stuff.length != 10
next_one = more_stuff.pop
puts "Adding: #{next_one}"
stuff.push(next_one)
puts "There are #{stuff.length} items now."
end
puts "There we go: #{stuff}"
puts "Let's do some things with stuff."
puts stuff[1]
puts stuff[-1] # whoah! fancy
puts stuff.pop
puts stuff.join(" ")
puts stuff[3..5].join("#")
puts stuff

55
exercises/ex39.rb Normal file
View File

@ -0,0 +1,55 @@
# create a mapping of state to abbreviation
states = {
"Oregon" => "OR",
"Florida" => "FL",
"California" => "CA",
"New York" => "NY",
"Michigan" => "MI"
}
# create a basic set of states and some cities in them
cities = {
"CA" => "San Francisco",
"MI" => "Detroit",
"FL" => "Jacksonville"
}
# add some more cities
cities["NY"] = "New York"
cities["OR"] = "Portland"
# puts out some cities
puts "-" * 10
puts "NY State has: #{cities["NY"]}"
puts "OR State has: #{cities["OR"]}"
# do it by using the state then cities dict
puts "-" * 10
puts "Michigan has: #{cities[states["Michigan"]]}"
puts "Florida has: #{cities[states["Florida"]]}"
# puts every city in state
puts "-" * 10
cities.each do |abbrev, city|
puts "#{abbrev} has the city #{city}"
end
# now do both at the same time
puts "-" * 10
states.each do |state, abbrev|
city = cities[abbrev]
puts "#{state} is abbreviated #{abbrev} and has city #{city}"
end
puts "-" * 10
# by default ruby says "nil" when something isn't in there
state = states["Texas"]
if !state
puts "Sorry, no Texas."
end
# default values using ||= with the nil result
city = cities["TX"]
city ||= "Does not exist"
puts "The city for state 'TX' is: #{city}"

15
exercises/ex4.rb Normal file
View File

@ -0,0 +1,15 @@
cars = 100
space_in_a_car = 4
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
puts "There are #{cars} cars available."
puts "There are only #{drivers} drivers available."
puts "There will be #{cars_not_driven} empty cars today."
puts "We can transport #{carpool_capacity} people today."
puts "We have #{passengers} to carpool today."
puts "We need to put about #{average_passengers_per_car} in each car."

25
exercises/ex40.rb Normal file
View File

@ -0,0 +1,25 @@
class Song
def initialize(lyrics)
@lyrics = lyrics
end
def sing_me_a_song
@lyrics.each do |line|
puts line
end
end
end
happy_bday = Song.new([
"Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"
])
bulls_on_parade = Song.new([
"They rally around tha family",
"With pockets full of shells"
])
happy_bday.sing_me_a_song
bulls_on_parade.sing_me_a_song

97
exercises/ex41.rb Normal file
View File

@ -0,0 +1,97 @@
require "open-uri"
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class ### < ###\nend" =>
"Make a class named ### that is-a ###.",
"class ###\n\tdef initialize(@@@)\n\tend\nend" =>
"class ### has-a initialize that takes @@@ parameters.",
"class ###\n\tdef ***(@@@)\n\tend\nend" =>
"class ### has-a function named *** that takes @@@ parameters.",
"*** = ###.new()" =>
"Set *** to an instance of class ###.",
"***.***(@@@)" =>
"From *** get the *** function, and call it with parameters @@@.",
"***.*** = '***'" =>
"From *** get the *** attribute and set it to '***'."
}
PHRASE_FIRST = ARGV[0] == "english"
URI.open(WORD_URL) { |f|
f.each_line do |word|
WORDS.push(word.chomp)
end
}
def craft_names(rand_words, snippet, pattern, caps = false)
names = snippet.scan(pattern).map do
word = rand_words.pop
caps ? word.capitalize : word
end
names * 2
end
def craft_params(rand_words, snippet, pattern)
names = (0...snippet.scan(pattern).length).map do
param_count = rand(1..3)
params = (0...param_count).map do |x|
rand_words.pop
end
params.join(", ")
end
names * 2
end
def convert(snippet, phrase)
rand_words = WORDS.sort_by { rand }
class_names = craft_names(rand_words, snippet, /###/, caps = true)
other_names = craft_names(rand_words, snippet, /\*\*\*/)
param_names = craft_params(rand_words, snippet, /@@@/)
results = []
[snippet, phrase].each do |sentence|
# fake class names, also copies sentence
result = sentence.gsub("###") do |x|
class_names.pop
end
# fake other names
result.gsub!("***") do |x|
other_names.pop
end
# fake parameter lists
result.gsub!(/@@@/) do |x|
param_names.pop
end
results.push(result)
end
results
end
# keep going until they hit CTRL-D
loop do
snippets = PHRASES.keys.sort_by { rand }
snippets.each do |snippet|
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST
question, answer = answer, question
end
print question, "\n\n> "
exit(0) unless $stdin.gets
puts "\nANSWER: %s\n\n" % answer
end
end

102
exercises/ex42.rb Normal file
View File

@ -0,0 +1,102 @@
# Animal is-a object
class Animal
def initialize(latin_name)
# Animal has-a latin_name
@latin_name = latin_name
end
end
# Dog is-a Animal
class Dog < Animal
def initialize(latin_name, name)
super(latin_name)
# Dog has-a name
@name = name
end
end
# Cat is-a Animal
class Cat < Animal
def initialize(latin_name, name)
super(latin_name)
# Cat has-a name
@name = name
end
attr_reader :name
end
# Person is-a object
class Person
def initialize(name, pet = nil)
# Person has-a name
@name = name
# Person has-a pet of some kind
@pet = pet
end
attr_accessor :pet
end
# Employee is-a Person
class Employee < Person
def initialize(name, salary)
super(name)
@salary = salary
end
end
# class Employee < Person
# def initialize(name, salary)
# # Employee has-a name
# super(name)
# # Employee has-a salary
# @salary = salary
# end
# end
# Fish is-a object
class Fish
end
# Salmon is-a Fish
class Salmon < Fish
end
# Halibut is-a Fish
class Halibut < Fish
end
# rover is-a Dog
rover = Dog.new("Latin", "Rover")
# satan is-a Cat
satan = Cat.new("Latin", "Satan")
# mary is-a Person
mary = Person.new("Mary")
# mary has-a Pet, satan
mary.pet = satan
# frank is-a Employee
frank = Employee.new("Frank", 120_000)
# frank has-a pet, rover
frank.pet = rover
# flipper is-a Fish
flipper = Fish.new
# crouse is-a Salmon
crouse = Salmon.new
# harry is-a Halibut
harry = Halibut.new
# fidget is-a cat
fidget = Cat.new("Latin", "Fidget")
# james is-a Person and has-a pet, Fidget
james = Person.new("James", fidget)
puts james.pet.name # Fidget

0
exercises/ex43.rb Normal file
View File

0
exercises/ex44.rb Normal file
View File

0
exercises/ex45.rb Normal file
View File

17
exercises/ex5.rb Normal file
View File

@ -0,0 +1,17 @@
name = "Zed A. Shaw"
age = 35 # not a lie in 2009
height = 74 # inches
weight = 180 # lbs
eyes = "Blue"
teeth = "White"
hair = "Brown"
puts "Let's talk about #{name}"
puts "He's #{height} inches tall."
puts "He's #{weight} pounds heavy."
puts "Actually that's not too heavy."
puts "He's got #{eyes} eyes and #{hair} hair."
puts "His teeth are usually #{teeth} depending on the coffee."
# this line is tricky, try to get it exactly right
puts "If I add #{age}, #{height}, and #{weight} I get #{age + height + weight}."

21
exercises/ex6.rb Normal file
View File

@ -0,0 +1,21 @@
types_of_people = 10
x = "There are #{types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = "Those who know #{binary} and those who #{do_not}."
puts x
puts y
puts "I said: #{x}."
puts "I also said: '#{y}'."
hilarious = false
joke_evaluation = "Isn't that joke so funny?! #{hilarious}"
puts joke_evaluation
w = "This is the left side of..."
e = "a string with a right side."
puts w + e

21
exercises/ex7.rb Normal file
View File

@ -0,0 +1,21 @@
puts "Mary had a little lamb."
puts "Its fleece was white as snow."
puts "And everywhere that Mary went."
puts "." * 10 # what'd that do?
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that print vs. puts on this line what's it do?
print end1 + end2 + end3 + end4 + end5 + end6
puts end7 + end8 + end9 + end10 + end11 + end12

14
exercises/ex8.rb Normal file
View File

@ -0,0 +1,14 @@
formatter = "%<first>s %<second>s %<third>s %<fourth>s"
puts format(formatter, first: 1, second: 2, third: 3, fourth: 4)
puts format(formatter, first: "one", second: "two", third: "three", fourth: "four")
puts format(formatter, first: true, second: false, third: true, fourth: false)
puts format(formatter, first: formatter, second: formatter, third: formatter, fourth: formatter)
puts format(
formatter,
first: "I had this thing.",
second: "That you could type up right.",
third: "But it didn't sing.",
fourth: "So I said goodnight."
)

14
exercises/ex9.rb Normal file
View File

@ -0,0 +1,14 @@
# Here's some new strange stuff, remember to type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
puts "Here are the days: #{days}"
puts "Here are the months: #{months}"
puts "
There's something going on here.
With this weird quote
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"