diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 000000000..30a393c94 Binary files /dev/null and b/.DS_Store differ diff --git a/day_1/.DS_Store b/day_1/.DS_Store new file mode 100644 index 000000000..8563bd3a1 Binary files /dev/null and b/day_1/.DS_Store differ diff --git a/day_1/README.md b/day_1/README.md index 034ae11da..a67fc82b7 100644 --- a/day_1/README.md +++ b/day_1/README.md @@ -48,19 +48,19 @@ This will open the day_1 directory in Atom. You should be able to see the direct 1. Check off the items below as you complete the steps you just read for each lesson. ***Remember to create a file containing your work for each lesson!*** - - [ ] [A Good First Program](https://learnrubythehardway.org/book/ex1.html) + - [**X**] [A Good First Program](https://learnrubythehardway.org/book/ex1.html) - - [ ] [Comments in Code](https://learnrubythehardway.org/book/ex2.html) + - [**X**] [Comments in Code](https://learnrubythehardway.org/book/ex2.html) - - [ ] [Numbers and Math](https://learnrubythehardway.org/book/ex3.html) + - [**X**] [Numbers and Math](https://learnrubythehardway.org/book/ex3.html) - - [ ] [Variables and Names](https://learnrubythehardway.org/book/ex4.html) + - [**X**] [Variables and Names](https://learnrubythehardway.org/book/ex4.html) - - [ ] [Strings](https://learnrubythehardway.org/book/ex5.html) + - [**X**] [Strings](https://learnrubythehardway.org/book/ex5.html) - - [ ] [More Strings](https://learnrubythehardway.org/book/ex6.html) + - [**X** ] [More Strings](https://learnrubythehardway.org/book/ex6.html) - - [ ] [Asking for Input](https://learnrubythehardway.org/book/ex11.html) + - [**X** ] [Asking for Input](https://learnrubythehardway.org/book/ex11.html) - [ ] Have you created 7 `ex.rb` files with your code in them? diff --git a/day_1/exercises/ex1.rb b/day_1/exercises/ex1.rb new file mode 100644 index 000000000..ebec88bd6 --- /dev/null +++ b/day_1/exercises/ex1.rb @@ -0,0 +1,7 @@ +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.' diff --git a/day_1/exercises/ex2.rb b/day_1/exercises/ex2.rb new file mode 100644 index 000000000..7a81319a2 --- /dev/null +++ b/day_1/exercises/ex2.rb @@ -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." diff --git a/day_1/exercises/ex3.rb b/day_1/exercises/ex3.rb new file mode 100644 index 000000000..e33aa12b5 --- /dev/null +++ b/day_1/exercises/ex3.rb @@ -0,0 +1,29 @@ +puts "I will now count my chickens:" + +# calculates 25 plus the result of 30/6 (5) +puts "Hens #{25.0 + 30 / 6}" +# calculates 100 minus the remainder of +# 75/4 (3) = 97 +puts "Roosters #{100.0 - 25 * 3 % 4}" + +puts "Now I will count the eggs:" + +# Follow the order of operations +puts 3.0 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 + +puts "Is it true that 3 + 2 < 5 - 7?" + +# Returns boolean result of 5 < -2 (false) +puts 3.0 + 2 < 5 - 7 + +# #{} allows calculations to be contained within strings in ruby +puts "What is 3 + 2? #{3.0 + 2}" +puts "What is 5 - 7? #{5.0 - 7}" + +puts "Oh, that's why it's false." + +puts "How about some more." + +puts "Is it greater? #{5.0 > -2}" +puts "Is it greater or equal? #{5.0 >= -2}" +puts "Is it less or equal? #{5.0 <= -2}" diff --git a/day_1/exercises/ex4.rb b/day_1/exercises/ex4.rb new file mode 100644 index 000000000..8b106b8d0 --- /dev/null +++ b/day_1/exercises/ex4.rb @@ -0,0 +1,23 @@ +# assign values to Variables +# integer +cars = 100 +# integer, these will be full cars with 3 passengers sharing the backseat +space_in_a_car = 4 +# integer +drivers = 30 +# integer +passengers = 90 +# integer +cars_not_driven = cars - drivers +# integer, variable is easier to understand and use in context than drivers +cars_driven = drivers +carpool_capacity = cars_driven * space_in_a_car +average_passengers_per_car = passengers / cars_driven + +# Print strings with values using #{variable_name} + +puts "There are #{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 need to put about #{average_passengers_per_car} in each car." diff --git a/day_1/exercises/ex5.rb b/day_1/exercises/ex5.rb new file mode 100644 index 000000000..56df03798 --- /dev/null +++ b/day_1/exercises/ex5.rb @@ -0,0 +1,23 @@ +# More practice with embedding variables in strings using #{} + +my_name = 'Zed A. Shaw' +my_age = 35 # not true now +my_height = 74 # inches +my_weight = 180 # pounds +my_eyes = 'blue' +my_teeth = 'white' +my_hair = 'brown' +my_weight_in_kg = my_weight / 2.20462 +my_height_in_cm = my_height * 2.54 + +puts "Let's talk about #{my_name}." +puts "He's #{my_height} inches tall." +puts "He's #{my_weight} pounds heavy." +puts "Actually that's not too heavy." +puts "He's got #{my_eyes} eyes and #{my_hair} hair." +puts "His teeth are usually #{my_teeth} depending on the coffee." + +# this line is tricky, try to et it exactly right +puts "If I add #{my_age}, #{my_height}, and #{my_weight} I get #{my_age + my_height + my_weight}." + +puts "Zed's weight in kg is #{my_weight_in_kg.round(1)}kg and his height in cm is #{my_height_in_cm.round(1)}cm." diff --git a/day_1/exercises/ex6.rb b/day_1/exercises/ex6.rb new file mode 100644 index 000000000..0da9ff6bd --- /dev/null +++ b/day_1/exercises/ex6.rb @@ -0,0 +1,23 @@ +# Exercise to practice working with strings + +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 diff --git a/day_1/exercises/ex7.rb b/day_1/exercises/ex7.rb new file mode 100644 index 000000000..31c6c8941 --- /dev/null +++ b/day_1/exercises/ex7.rb @@ -0,0 +1,12 @@ +# This is Exercise 11 in Ruby the Hard Way + +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} old, #{height} tall and #{weight} heavy." + +# Use gets.chomp.to_i to get a string from a user and convert to integer diff --git a/day_1/exercises/interpolation.rb b/day_1/exercises/interpolation.rb index c7f4f47df..dc7911a1b 100644 --- a/day_1/exercises/interpolation.rb +++ b/day_1/exercises/interpolation.rb @@ -11,15 +11,15 @@ p "The #{team} are #{name}'s favorite Quidditch team" # Write code that uses the variables below to form a string that reads -# "The quick red fox jumped over the lazy brown dog": +# "The quick red fox jumped over the lazy brown dog.": speedy = "quick red fox" slow_poke = "lazy brown dog" -p # YOUR CODE HERE +puts "The #{speedy} jumped over the #{slow_poke}." # Write code that uses the variables below to form a string that reads # "In a predictable result, the tortoise beat the hare!": slow_poke = "tortoise" speedy = "hare" -# YOUR CODE HERE +puts "In a predictable result, the #{slow_poke} beat the #{speedy}!" diff --git a/day_1/exercises/loops.rb b/day_1/exercises/loops.rb index 90dc15ab1..fde248f09 100644 --- a/day_1/exercises/loops.rb +++ b/day_1/exercises/loops.rb @@ -10,9 +10,12 @@ # Write code that prints the sum of 2 plus 2 seven times: 7.times do - # YOUR CODE HERE + puts 2 + 2 end # Write code that prints the phrase 'She sells seashells down by the seashore' # ten times: -# YOUR CODE HERE +sally = "She sells seashells down by the seashore" +10.times do + puts sally +end diff --git a/day_1/exercises/numbers.rb b/day_1/exercises/numbers.rb index 9a5468a31..141ad74ad 100644 --- a/day_1/exercises/numbers.rb +++ b/day_1/exercises/numbers.rb @@ -4,13 +4,14 @@ # `ruby day_1/exercises/numbers.rb` # Example: Write code that prints the result of the sum of 2 and 2: -p 2 + 2 +#p 2 + 2 # Write code that prints the result of 7 subtracted from 83: -p #YOUR CODE HERE + +puts "7 subtracted from 83 is #{83 - 7}." #YOUR CODE HERE # Write code that prints the result of 6 multiplied by 53: -# YOUR CODE HERE +puts "6 times 53 is #{6 * 53}." # Write code that prints the result of the modulo of 10 into 54: -# YOUR CODE HERE +puts "The remainder of 54 divided by 10 (modulo) is #{54 % 10}." diff --git a/day_1/exercises/strings.rb b/day_1/exercises/strings.rb index f2f903ffc..70eed3ddf 100644 --- a/day_1/exercises/strings.rb +++ b/day_1/exercises/strings.rb @@ -7,7 +7,7 @@ p "Alan Turing" # Write code that prints `Welcome to Turing!` to the terminal: -p #YOUR CODE HERE +puts "Welcome to Turing!" #YOUR CODE HERE # Write code that prints `99 bottles of pop on the wall...` to the terminal: -# YOUR CODE HERE +puts "99 bottles of soda on the wall..." diff --git a/day_1/exercises/variables.rb b/day_1/exercises/variables.rb index a1e45bb26..98f109fc6 100644 --- a/day_1/exercises/variables.rb +++ b/day_1/exercises/variables.rb @@ -1,6 +1,6 @@ # In the below exercises, write code that achieves # the desired result. To check your work, run this -# file by entering the following command in your terminal: +# file by entering the following command in your terminal: # `ruby day_1/exercises/variables.rb` # Example: Write code that saves your name to a variable and @@ -11,19 +11,20 @@ # Write code that saves the string 'Dobby' to a variable and # prints what that variable holds to the terminal: house_elf = "Dobby" -# YOUR CODE HERE +puts house_elf # Write code that saves the string 'Harry Potter must not return to Hogwarts!' # and prints what that variable holds to the terminal: -# YOUR CODE HERE +dobby_warning = "Harry Potter must not return to Hogwarts." +puts dobby_warning # Write code that adds 2 to the `students` variable and # prints the result: students = 22 -# YOUR CODE HERE -p students +students = students + 2 +puts students # Write code that subracts 2 from the `students` variable and # prints the result: -# YOUR CODE HERE -p students +students = students - 2 +puts students diff --git a/day_1/questions.md b/day_1/questions.md index 73700e323..f045c56aa 100644 --- a/day_1/questions.md +++ b/day_1/questions.md @@ -1,17 +1,29 @@ ## Day 1 Questions 1. How would you print the string `"Hello World!"` to the terminal? - +'''ruby +puts "Hello World!" +''' 1. What character is used to indicate comments in a ruby file? - +"#" 1. Explain the difference between an integer and a float? - +An integer is a whole number (1, 5, -3) and a float contains a decimal (1.5, 5.3, 0.01) 1. In the space below, create a variable `animal` that holds the string `"zebra"` - +'''ruby +animal = "zebra" +''' 1. How would you print the string `"zebra"` using the variable that you created above? - +'''ruby +puts animal +''' 1. What is interpolation? Use interpolation to print a sentence using the variable `animal`. - +Interpolation in ruby is including results of code within a string, such as the results of variables and calculations. +'''ruby +puts "Can you draw a #{animal}?" +''' +(I tried to look up a way to check if the first letter of the string was a consonant or vowel to make an if/else for the article a/an, but needed to move on before solving) 1. What method is used to get input from a user? - +gets.chomp 1. Name and describe two common string methods: + * .length returns number of characters in a string + * .split breaks a string into parts and puts into an array; can also take an argument diff --git a/day_2/.DS_Store b/day_2/.DS_Store new file mode 100644 index 000000000..8563bd3a1 Binary files /dev/null and b/day_2/.DS_Store differ diff --git a/day_2/array_methods.md b/day_2/array_methods.md new file mode 100644 index 000000000..570c09b46 --- /dev/null +++ b/day_2/array_methods.md @@ -0,0 +1,30 @@ +### Common Array Methods +###### Mod 1 Pre-work, Day 2 + +.sort -- if elements are strings, returns new alphabetized array + +.each -- iterates through each element + ```ruby + animals = ["cat", "dog", "bird", "snake"] + animals.each {|x| print x, " | "} + ``` + ``` + cat | dog | bird | snake + ``` + +.join -- connects string elements into one strong + +.include?() -- find if an array contains an element + +.first -- returns first element +.last -- returns last element + +.length .count .size -- returns number of elements + +.insert(position, element(s)) -- inserts one or more elements at the specified position + +.unshift -- add to the beginning of an array + +.pop -- removes and returns last element + +.uniq -- removes duplicates from array diff --git a/day_2/exercises/arrays.rb b/day_2/exercises/arrays.rb index f572a5ae6..61e70ee18 100644 --- a/day_2/exercises/arrays.rb +++ b/day_2/exercises/arrays.rb @@ -6,35 +6,38 @@ # Example: Write code that stores an array in a variable, # then prints that array: animals = ["Zebra", "Giraffe", "Elephant"] -p animals +puts animals # Write code that stores an array of states in a variable, # then prints that array: -states = #YOUR CODE HERE -p states +states = ["Arizona", "Colorado", "Tennessee", "Wisconsin"] +puts states # Write code that stores an array of foods in a variable, # then prints that array: -# YOUR CODE HERE +foods = ["rice", "soba", "udon", "ramen"] +puts foods # Example: Write code that prints the number of elements # in your above array of animals: -p animals.count +puts animals.count # Write code that prints the number of elements # in your above array of foods: -# YOUR CODE HERE +puts foods.size # Write code that prints "Zebra" from your animals array: -# YOUR CODE HERE +puts animals[0] +#puts animals.first # Write code that prints the last item of your foods array: -# YOUR CODE HERE +puts foods.last +#puts foods[-1] # Write code that adds "lion" to your animals array -# and prints the result (Hint- use a method): -# YOUR CODE HERE +animals << "lion" +puts animals.last # Write code that removes the last element from your foods array # and prints the result (Hint- use a method): -# YOUR CODE HERE +foods.pop diff --git a/day_2/exercises/hard_way_ex28_boolean_practice.rb b/day_2/exercises/hard_way_ex28_boolean_practice.rb new file mode 100644 index 000000000..b16351088 --- /dev/null +++ b/day_2/exercises/hard_way_ex28_boolean_practice.rb @@ -0,0 +1,48 @@ +# Logic exercises from +# https://learnrubythehardway.org/book/ex28.html + +# Two incorrect answers, easily reached correct after rereading + +#1 true +puts true && true +#2 false +puts false && true +#3 false +puts 1 == 1 && 2 == 1 +#4 true +puts "test" == "test" +#5 true +puts 1 == 1 || 2 != 1 +puts "" +#6 true +puts true && 1 == 1 +#7 false +puts false && 0 != 0 +#8 true +puts true || 1 == 1 +#9 false +puts "test" == "testing" +#10 false +puts 1 != 0 && 2 == 1 +puts "" +#11 true +puts "test" != "testing" +#12 false +puts "test" == 1 +#13 true +puts !(true && false) +#14 false +puts !(1 == 1 && 0 != 1) +#15 false +puts !(10 == 1 || 1000 == 1000) +puts "" +#16 false +puts !(1 != 10 || 3 == 4) +#17 true +puts !("testing" == "testing" && "Zed" == "Cool Guy") +#18 true +puts 1 == 1 && (!("testing" == 1 || 1 == 0)) +#19 false +puts "chunky" == "bacon" && (!(3 == 4 || 3 == 3)) +#20 false +puts 3 == 3 && (!("testing" == "testing" || "Ruby" == "Fun")) diff --git a/day_2/exercises/iteration.rb b/day_2/exercises/iteration.rb index a801cb4fc..150533bf1 100644 --- a/day_2/exercises/iteration.rb +++ b/day_2/exercises/iteration.rb @@ -15,14 +15,20 @@ # "The is awesome!" for each animal: animals.each do |animal| - # YOUR CODE HERE + puts "The " + animal + " is awesome!" end -# Write code that stores an array of foods in a variable, +# Write code that stores an array of foods in a variable, # then iterates over that array to print # "Add to shopping list" for each food item: -# YOUR CODE HERE +shopping_list = %w{avocados tomatoes garlic apples bread tortillas beans coffee} +shopping_list.each do |food| + puts "Add #{food} to shopping list" +end -# Write code that stores an array of numbers in a variable, -# then iterates over that array to print doubles of each number: -# YOUR CODE HERE +# Write code that stores an array of numbers in a variable, +# then iterates over that array to print doubles of each number: +my_numbers = [10, 100, 1000, 10000] +my_numbers.each do |number| + puts number * 2 +end diff --git a/day_2/iteration_and_each_exercises.rb b/day_2/iteration_and_each_exercises.rb new file mode 100644 index 000000000..40cdde6b8 --- /dev/null +++ b/day_2/iteration_and_each_exercises.rb @@ -0,0 +1,74 @@ +# Joe Mecha jwmecha@gmail.com +# Solutions to exercises from +# https://backend.turing.io/module1/lessons/iteration_and_each + +numbers = [1, 2, 3, 4] +puts "Prints doubles of each element in the array." +numbers.each do |a| + puts a * 2 +end + +puts "Prints triples of each element in the array." +numbers.each do |a| + puts a * 3 +end + +puts "Prints only even elements in the array." + numbers.each do |a| + puts a if a.even? +end + +puts "Prints only odd elements in the array." +numbers.each do |a| + puts a if a.odd? +end + +puts "Creates new array of doubled elements from original array. Prints new array." +doubled = Array.new +numbers.each do |a| + doubled.push(a * 2) +end +puts doubled + +puts "---" +puts "Prints only first name portion of full name elements in the array." +names = ["Alice Smith", "Bob Evans", "Roy Rogers"] +separated_names = Array.new +names.each do |name| + separated_names << name.split() +end +separated_names.each do |name| + puts name.first +end + +puts "" +puts "Prints only last name portion of full name elements in the array." +names = ["Alice Smith", "Bob Evans", "Roy Rogers"] +separated_names = Array.new +names.each do |name| + separated_names << name.split() +end +separated_names.each do |name| + puts name.last +end + +puts "" +puts "Prints only initials of full name elements in the array." +names = ["Alice Smith", "Bob Evans", "Roy Rogers"] +names.each do |name| + name = name.gsub(/[a-z]/, "").gsub(/\s/, "") + puts name +end + +# Changed .gsub(/[^A-Z]/, "") to gsub(/[a-z]/, "").gsub(/\s/, "") +# because it's easier to understand + +puts "" +puts "Prints the total number of characters in the array." +names = ["Alice Smith", "Bob Evans", "Roy Rogers"] +total_characters = 0 +names.each do |name| + name = name.gsub(/\s/, "") + total_characters = total_characters + name.length +end +puts total_characters diff --git a/day_2/questions.md b/day_2/questions.md index a179f0b04..3e081af61 100644 --- a/day_2/questions.md +++ b/day_2/questions.md @@ -1,17 +1,39 @@ ## Day 2 Questions 1. Create an array containing the following strings: `"zebra", "giraffe", "elephant"`. - +```ruby +["zebra", "giraffe", "elephant"] +``` 1. Save the array you created above to a variable `animals`. - +```ruby +animals = ["zebra", "giraffe", "elephant"] +``` 1. Using the array `animals`, how would you access `"giraffe"`? - +```ruby +animals[1] +``` 1. How would you add `"lion"` to the `animals` array? - +```ruby +animals << "lion" +``` +or +```ruby +animals.push("lion") +``` 1. Name and describe two additional array methods: - + * .unshift adds element to start of array + * .uniq removes duplicate elements from array + * .length .count .size number of elements in array 1. What are the boolean values in Ruby? - + * true, false + * There are many terms for making boolean arguments: && and, || or, ! not, != not equal, == equal, >= greater-than-equal, <= less-than-equal 1. In Ruby, how would you evaluate if `2` is equal to `25`? What is the result of this evaluation? - +```ruby +2 == 25 +``` +false 1. In Ruby, how would you evaluate if `25` is greater than `2`? What is the result of this evaluation? +```ruby +25 > 2 +``` +true diff --git a/day_3/.DS_Store b/day_3/.DS_Store new file mode 100644 index 000000000..8563bd3a1 Binary files /dev/null and b/day_3/.DS_Store differ diff --git a/day_3/exercises/exercise29_what_if.rb b/day_3/exercises/exercise29_what_if.rb new file mode 100644 index 000000000..3ee624f28 --- /dev/null +++ b/day_3/exercises/exercise29_what_if.rb @@ -0,0 +1,35 @@ +# Exercise 29: What If from "the Hard Way" + +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 on!" +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 diff --git a/day_3/exercises/exercise30_else_and_if.rb b/day_3/exercises/exercise30_else_and_if.rb new file mode 100644 index 000000000..bc83d14af --- /dev/null +++ b/day_3/exercises/exercise30_else_and_if.rb @@ -0,0 +1,27 @@ +# Exercise 30: Else and If from "the Hard Way" + +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 decide" +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 diff --git a/day_3/exercises/exercise31_making_decisions.rb b/day_3/exercises/exercise31_making_decisions.rb new file mode 100644 index 000000000..0b76bad8b --- /dev/null +++ b/day_3/exercises/exercise31_making_decisions.rb @@ -0,0 +1,41 @@ +# Exercise 31: Making Decisions from "the Hard Way" + +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, doings %s is probably better. Bear runs away." % bear + end + +elsif door == "2" + puts "You stare into the endless abyss at Cthulu'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 diff --git a/day_3/exercises/if_statements.rb b/day_3/exercises/if_statements.rb index a80b96840..dc538921f 100644 --- a/day_3/exercises/if_statements.rb +++ b/day_3/exercises/if_statements.rb @@ -3,7 +3,7 @@ # file by entering the following command in your terminal: # `ruby day_3/exercises/if_statements.rb` -# Example: Using the weather variable below, write code that decides +# Example: Using the weather variable below, write code that decides # what you should take with you based on the following conditions: # if it is sunny, print "sunscreen" # if it is rainy, print "umbrella" @@ -26,6 +26,19 @@ # Experiment with manipulating the value held in variable 'weather' # to print something other than 'coat' +weather = 'smoky' + +if weather == 'sunny' + p "sunscreen" +elsif weather == 'rainy' + p "umbrella" +elsif weather == 'snowy' + p "coat" +elsif weather == 'icy' + p "yak traks" +else + p "good to go!" +end ################## @@ -35,7 +48,7 @@ # Right now, the program will print # out both "I have enough money for a gumball" and -# "I don't have enough money for a gumball". Write a +# "I don't have enough money for a gumball". Write a # conditional statement that prints only one or the other. # Experiment with manipulating the value held within num_quarters @@ -43,13 +56,15 @@ num_quarters = 0 -puts "I have enough money for a gumball" -puts "I don't have enough money for a gumball" - +if num_quarters >= 2 + puts "I have enough money for a gumball" +else + puts "I don't have enough money for a gumball" +end ##################### # Using the variables defined below, write code that will tell you -# if you have the ingredients to make a pizza. A pizza requires +# if you have the ingredients to make a pizza. A pizza requires # at least two cups of flour and sauce. # You should be able to change the variables to achieve the following outputs: @@ -61,5 +76,11 @@ # Experiment with manipulating the value held within both variables # to make sure all above conditions output what you expect. -cups_of_flour = 1 +cups_of_flour = 2 has_sauce = true + +if cups_of_flour >= 2 && has_sauce == true + puts "I can make pizza." +else + puts "I cannot make pizza." +end diff --git a/day_3/questions.md b/day_3/questions.md index db6170fa7..d613220ae 100644 --- a/day_3/questions.md +++ b/day_3/questions.md @@ -1,13 +1,41 @@ ## Day 3 Questions 1. What is a conditional statement? Give three examples. - +A conditional statement returns _true_ or _false_. There are several conditional operators: + * == equal + * > greater than, < less than + * >= greater than or equal + * <= less than or equal + * && and (all statements true to return true) + * || or (at least one statement true to return true) 1. Why might you want to use an if-statement? - +If-statements create branches in code. Based on some condition, run this code, otherwise run some other code. For example, if a typed password matches the stored password, unlock an account. 1. What is the Ruby syntax for an if statement? - +``` +if (conditional statement) + # indented code here (block) +elsif (different conditional statement) + # different code here +else (if "none of the above") + # some other code +end +``` +There is no limit to the number of _elsif_, but there can only be one _else_. 1. How do you add multiple conditions to an if statement? - +With the conditional operators 'and' (&&) or 'or' (||) 1. Provide an example of the Ruby syntax for an if/elsif/else statement: +```ruby +distance_in_mi = 150 +if distance_in_mi >= 100 + puts "We're not even close." + elsif distance_in_mi <= 99 && distance_in_mi >= 51 + puts "Still a ways to go." + elsif distance_in_mi <= 50 && >= 30 + puts "Getting closer." + else + puts "Not much farther." +end +``` 1. Other than an if-statement, can you think of any other ways we might want to use a conditional statement? +For creating _loops_? Does that count as another way? At this time it's the only idea I have. diff --git a/day_4/exercises/Day4_launchschool_methods.rb b/day_4/exercises/Day4_launchschool_methods.rb new file mode 100644 index 000000000..76f20b4ce --- /dev/null +++ b/day_4/exercises/Day4_launchschool_methods.rb @@ -0,0 +1,48 @@ +# Method example with default parameter when no argument is passed +def say(words='hello') + puts words + '.' +end + +say() +say("hi") +say("how are you") +say("I'm fine") + +# Does "a's" value get reassigned? No. +def some_method(number) + number = 7 # this is implicitly returned by the method +end + +a = 5 +some_method(a) +puts a + +# Defines method "add_three" and then calls .times method +def add_three(n) + n + 3 +end + +add_three(5).times { puts "This should print 8 times."} + +# Methods for add and subtract +def add(a, b) + a + b +end + +def subtract(a, b) + a - b +end + +# Methods as arguments in other method example +add(subtract(80, 10), multiply(subtract(20, 6), add(30, 5))) +# returns 4550 + +# Write a program that prints a greeting message +def greeting(name) + puts "Hello #{name}" +end + +# Write a program "multiply" +def multiply(a, b) + a * begin +end diff --git a/day_4/exercises/ex18.rb b/day_4/exercises/ex18.rb new file mode 100644 index 000000000..d6525ee05 --- /dev/null +++ b/day_4/exercises/ex18.rb @@ -0,0 +1,28 @@ +# The Hard Way, Exercise 18 +# https://learnrubythehardway.org/book/ex18.html + +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() diff --git a/day_4/exercises/ex19.rb b/day_4/exercises/ex19.rb new file mode 100644 index 000000000..e7240f8bb --- /dev/null +++ b/day_4/exercises/ex19.rb @@ -0,0 +1,53 @@ +# The Hard Way, Ex. 19: Functions and Variables +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) + +# Instead of feeding values directly, use variables +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) + +# Calculations and other methods can be used as arguments inside of other methods +puts "We can even do math inside too:" +cheese_and_crackers(10 + 20, 5 + 6) + +# Self explanatory +puts "And we an combine the two, variables and math:" +cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) + + +puts "--------------------------" +puts "\n" + +# Practice exercise: write one more function and run 10 different ways. +def log_exercise(distance_in_km, time_in_min) + puts "Today I ran #{distance_in_km} km." + puts "Today's run was #{time_in_min} minutes." + puts "Today's average pace was #{(time_in_min / distance_in_km).round(2)} minutes per km." +end + +puts "1. directly" +log_exercise(10.0, 51.0) + +puts "2. with variables" +monday_km = 7.5 +monday_min = 42.0 +log_exercise(monday_km, monday_min) + +puts "3. Calculations" +log_exercise(7 + 3, 42 + 17) + +puts "4. Variables and math" +log_exercise(monday_km + 3, monday_min + 17) + +puts "5. I don't have ideas for 6 additional ways to run. I need to move on to other work." diff --git a/day_4/exercises/ex21.rb b/day_4/exercises/ex21.rb new file mode 100644 index 000000000..1b8781533 --- /dev/null +++ b/day_4/exercises/ex21.rb @@ -0,0 +1,40 @@ +# The Hard Way, Ex 21: Functions can return something +def add(a, b) + puts "Adding #{a} + #{b}" + return a + b +end + +def subtract(a, b) + puts "Subtracting #{a} - #{b}" + return a - b +end + +def multiply(a, b) + puts "Multiplying #{a} * #{b}" + return a * b +end + +def divide(a, b) + puts "Dividing #{a} / #{b}" + return 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 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?" + +# Another formula +puts subtract(add(24, divide(34, 100)), 1023) diff --git a/day_4/exercises/methods.rb b/day_4/exercises/methods.rb index 6ed338e5d..7791b795c 100644 --- a/day_4/exercises/methods.rb +++ b/day_4/exercises/methods.rb @@ -12,16 +12,25 @@ def print_name # Write a method that takes a name as an argument and prints it: def print_name(name) - # YOUR CODE HERE + puts name end print_name("Albus Dumbledore") -# Write a method that takes in 2 numbers as arguments and prints +# Write a method that takes in 2 numbers as arguments and prints # their sum. Then call your method: -# YOUR CODE HERE +def add(a, b) + puts a + b +end + +add(10, -3) -# Write a method that takes in two strings as arguments and prints -# a concatenation of those two strings. Example: The arguments could be -# (man, woman) and the end result might output: "When Harry Met Sally". +# Write a method that takes in two strings as arguments and prints +# a concatenation of those two strings. Example: The arguments could be +# (man, woman) and the end result might output: "When Harry Met Sally". # Then call your method: +def mixed_drink(base, mixer) + puts "This is my two ingredient cocktail. It's a #{base} and #{mixer}." +end + +mixed_drink("whiskey", "ginger ale") diff --git a/day_4/questions.md b/day_4/questions.md index af17ab4da..ad268e8db 100644 --- a/day_4/questions.md +++ b/day_4/questions.md @@ -1,11 +1,21 @@ ## Day 4 Questions 1. In your own words, what is the purpose of a method? - +Methods eliminate the need to write the same code over and over when the same set of steps is needed. After defining a method, only the method name is needed to run the same code each time (and data for any arguments). 1. Create a method named `hello` that will print `"Sam I am"`. - +```ruby +def hello + puts "Sam I am" +end +``` 1. Create a method named `hello_someone` that takes an argument of `name` and prints `"#{name} I am"`. - +```ruby +def hello_someone(name) + puts "#{name} I am" +``` 1. How would you call or execute the method that you created above? - +```ruby +hello_someone(Sam) +``` 1. What questions do you have about methods in Ruby? +None at the moment. I had been somewhat confused by parameters, but the first reading "Learning Ruby Methods" gave a very clear explanation of methods. diff --git a/day_5/exercises/ex39_hashes.rb b/day_5/exercises/ex39_hashes.rb new file mode 100644 index 000000000..ee32c6458 --- /dev/null +++ b/day_5/exercises/ex39_hashes.rb @@ -0,0 +1,108 @@ +# The Hard Way, Exercise 39: Hashes + +# create a mapping (associations) 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']}" + +# puts some states +puts '-' * 10 +puts "Michigan's abbreviation is: #{states['Michigan']}" +puts "Florida's abbreviation is: #{states['Florida']}" + +# do it all by using the state, then cities dict +puts '-' * 10 +puts "Michigan has: #{cities[states['Michigan']]}" +puts "Florida has: #{cities[states['Florida']]}" + +# puts every state abbreviation +puts '-' * 10 +states.each do |state, abbrev| + puts "#{state} is abbreviated #{abbrev}" +end + +# 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 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 the state 'TX' is #{city}" + + +# Study drill 1: do the same kind of mapping +cities = { + "Nagano" => "Matsumoto", + "Niigata" => "Joetsu", + "Yamanashi" => "Hokuto", + "Hokkaido" => "Sapporo", + "Miyagi" => "Sendai" +} + +stations = { + "Matsumoto" => "Minami Matsumoto Sta.", + "Joetsu" => "Takada Sta.", + "Hokuto" => "Hokuto Sta." +} + +# BE CAREFUL = NOT => !!! +stations["Sapporo"] = "Odori Sta." +stations["Miyagi"] = "Miyaginodori Sta." + +puts "-" * 5 +puts "Nagano Prefecture has #{cities["Nagano"]}" +puts "Niigata Prefecture has #{cities["Niigata"]}" + +puts "-" *5 +puts "One station in Matsumoto is #{stations["Matsumoto"]}" +puts "One station in Sapporo is #{stations["Sapporo"]}" + +puts "Nagano has #{stations[cities["Nagano"]]}" + +puts "-" * 5 +cities.each do |prefecture, city| + puts "#{city} is located in #{prefecture}" +end + +# A couple more methods +puts cities.keys + +puts stations.values diff --git a/day_5/exercises/hashes.rb b/day_5/exercises/hashes.rb index 99fcebb77..df5f9e112 100644 --- a/day_5/exercises/hashes.rb +++ b/day_5/exercises/hashes.rb @@ -1,6 +1,6 @@ # In the below exercises, write code that achieves # the desired result. To check your work, run this -# file by entering the following command in your terminal: +# file by entering the following command in your terminal: # `ruby day_5/exercises/hashes.rb` # Example: Write code that prints a hash holding grocery store inventory: @@ -8,21 +8,22 @@ p foods # Write code that prints a hash holding zoo animal inventory: -zoo = #YOUR CODE HERE +zoo = {"penguin" => 10, "walrus" => 1, "kangaroo" => 3, "giraffe" => 2, "lion" => 3} p zoo -# Write code that prints all of the 'keys' of the zoo variable +# Write code that prints all of the 'keys' of the zoo variable # you created above: -# YOUR CODE HERE - -# Write code that prints all of the 'values' of the zoo variable +puts zoo.keys +# Write code that prints all of the 'values' of the zoo variable # you created above: -# YOUR CODE HERE +puts zoo.values -# Write code that prints the value of the first animal of the zoo variable +# Write code that prints the value of the first animal of the zoo variable # you created above: -# YOUR CODE HERE +puts "There are #{zoo["penguin"]} penguins in the zoo." # Hashes are unordered, +#so is there a way to target the first value without specifying its key? -# Write code that adds an animal to the zoo hash. +# Write code that adds an animal to the zoo hash. # Then, print the updated hash: -# YOUR CODE HERE +zoo["alligator"] = 8 +p zoo diff --git a/day_5/questions.md b/day_5/questions.md index d059e12c6..d58da8f20 100644 --- a/day_5/questions.md +++ b/day_5/questions.md @@ -1,13 +1,32 @@ ## Day 5 Questions 1. What is a Hash, and how is it different from an Array? +A hash is a collection of associated pairs known as keys and values. Unlike an array, the elements of a hash are not ordered. Keys and values are linked by the _hash rocket_ symbol (_=>_), or in the current version of ruby (2.7), by a _colon_ (_:_) 1. In the space below, create a Hash stored to a variable named `pet_store`. This hash should hold an inventory of items and the number of that item that you might find at a pet store. +```ruby +pet_store = {"cheap cat food" => 500, "expensive cat food" => 250, "Meow Mix" => 25, "spiked dog collar" => 30, "ridiculous dog costume" => 97} +``` + 1. Given the following `states = {"CO" => "Colorado", "IA" => "Iowa", "OK" => "Oklahoma"}`, how would you access the value `"Iowa"`? +```ruby +states["IA"] +``` +OR +```ruby +states.fetch("IA") +``` 1. With the same hash above, how would we get all the keys? How about all the values? +```ruby +states.keys +states.values +``` + 1. What is another example of when we might use a hash? In your example, why is a hash better than an array? +A collection of names and usernames. The order doesn't matter, and it is **searchable**. 1. What questions do you still have about hashes? +None, but still need more practice. Need more reps to avoid syntax errors (e.g. = vs =>) diff --git a/day_6/.DS_Store b/day_6/.DS_Store new file mode 100644 index 000000000..8563bd3a1 Binary files /dev/null and b/day_6/.DS_Store differ diff --git a/day_6/exercises/burrito.rb b/day_6/exercises/burrito.rb index 967f68b6c..b23dc8036 100644 --- a/day_6/exercises/burrito.rb +++ b/day_6/exercises/burrito.rb @@ -1,4 +1,4 @@ -# Add the following methods to this burrito class and +# Add the following methods to this burrito class and # call the methods below the class: # 1. add_topping # 2. remove_topping @@ -11,9 +11,29 @@ def initialize(protein, base, toppings) @base = base @toppings = toppings end + + def add_topping(topping) + @toppings << topping + end + + def remove_topping(topping) + @toppings.delete(topping)# code here + end + + def change_protein(protein) + @protein = protein + end end dinner = Burrito.new("Beans", "Rice", ["cheese", "salsa", "guacamole"]) p dinner.protein p dinner.base p dinner.toppings + +puts "-" * 10 +dinner.add_topping("hot sauce") +p dinner.toppings +dinner.remove_topping("hot sauce") +p dinner.toppings +dinner.change_protein("portobello") +puts dinner.protein diff --git a/day_6/exercises/dog.rb b/day_6/exercises/dog.rb index 03221314d..1b78e5423 100644 --- a/day_6/exercises/dog.rb +++ b/day_6/exercises/dog.rb @@ -1,5 +1,5 @@ # In the dog class below, write a `play` method that makes -# the dog hungry. Call that method below the class, and +# the dog hungry. Call that method below the class, and # print the dog's hunger status. class Dog @@ -19,6 +19,10 @@ def bark def eat @hungry = false end + + def play + @hungry = true + end end fido = Dog.new("Bernese", "Fido", 4) @@ -28,3 +32,6 @@ def eat p fido.hungry fido.eat p fido.hungry +puts "-" * 10 +fido.play +puts fido.hungry diff --git a/day_6/exercises/dog_class_instance_example.rb b/day_6/exercises/dog_class_instance_example.rb new file mode 100644 index 000000000..d4673edcd --- /dev/null +++ b/day_6/exercises/dog_class_instance_example.rb @@ -0,0 +1,34 @@ +# From the Day 6 questions.md file +# Referred to https://launchschool.com/books/oo_ruby/read/classes_and_objects_part1 +# To fix errors in code + +class SomeDoggo + attr_accessor :name, :age, :has_energy + + def initialize(name, age, has_energy) + @name = name + @age = age + @has_energy = has_energy + end + + def dog_tag + puts "This dog's name is #{name}." + end + + def has_birthday + self.age += 1 # created error until ".self" added + puts "Today #{name} is #{age} years old." + end + + def go_running + self.has_energy = false # created undefined error until ".self" added + end +end + + +greg = SomeDoggo.new("Greg", 3, true) + +greg.dog_tag +greg.has_birthday +greg.go_running +puts greg.has_energy diff --git a/day_6/exercises/my_car.rb b/day_6/exercises/my_car.rb new file mode 100644 index 000000000..191300194 --- /dev/null +++ b/day_6/exercises/my_car.rb @@ -0,0 +1,64 @@ +# Exercise from https://launchschool.com/books/oo_ruby/read/classes_and_objects_part1 +class MyCar +# attr_accessor :model, :year, :color + attr_accessor :color + attr_reader :year + + def initialize(model, year, color) + @model = model + @year = year + @color = color + @current_speed = 0 + end + + def increase_speed(number) + @current_speed += number + puts "#{@model} accelerated #{number} mph and the new speed is #{@current_speed}." + end + + def brake(number) + @current_speed -= number + puts "#{@model} has braked #{number} mph and the new speed is #{@current_speed}." + end + + def current_speed + puts "#{@model} is going #{@current_speed} mph." + end + + def turn_off + @current_speed = 0 + puts "The #{@model} has stopped, parked, and the engine shut off." + end + + def spray_paint(color) + self.color = color + puts "The car has been painted #{color}." + end +# def change_color(color) +# @color = color +# puts "The color is #{color}." +# end + +# def print_year +# puts "The car's year is #{year}" +# end +end + +# create instance +fiero = MyCar.new("Fiero", "1985", "silver") + +# try class methods +fiero.increase_speed(70) +fiero.current_speed +fiero.brake(5) +fiero.current_speed + +fiero.turn_off +fiero.current_speed + +fiero.color = "black" +puts fiero.color +puts fiero.year + +puts "-" * 10 +fiero.spray_paint("red") diff --git a/day_6/exercises/person.rb b/day_6/exercises/person.rb index 2c26e9570..c200a30ed 100644 --- a/day_6/exercises/person.rb +++ b/day_6/exercises/person.rb @@ -1,5 +1,32 @@ -# Create a person class with at least 2 attributes and 2 behaviors. +# Create a person class with at least 2 attributes and 2 behaviors. # Call all person methods below the class and print results # to the terminal that show the methods in action. -# YOUR CODE HERE +class SomePerson + attr_accessor :name, :occupation, :fav_hobby + + def initialize(name, occupation, fav_hobby) + @name = name + @occupation = occupation + @fav_hobby = fav_hobby + end + + def display_info + puts "This person's name is #{@name}, their current job is #{@occupation}, and their favorite hobby is #{@fav_hobby}." + end + + def changes_occupation(job) + @occupation = job + puts "#{@name}'s new job is #{@occupation}." + end + + def new_hobby(hobby) + @fav_hobby = hobby + puts "#{@fav_hobby.capitalize} is their favorite hobby now." + end +end + +guy = SomePerson.new("This guy", "beachcomber", "flying kites") +guy.display_info +guy.changes_occupation("life guard") +guy.new_hobby("doing push ups") diff --git a/day_6/questions.md b/day_6/questions.md index f58ca5f71..f8249a8cd 100644 --- a/day_6/questions.md +++ b/day_6/questions.md @@ -1,13 +1,49 @@ ## Day 6 Questions 1. In your own words, what is a Class? +A class is like a template for creating objects. It contains information on attributes (characteristics) and methods (behaviors) 1. What is an attribute of a Class? +An attribute of a class is a characteristic that will have a value of a single data type. 1. What is behavior of a Class? +The behavior of a class are its methods -- what it is able to do. 1. In the space below, create a Dog class with at least 2 attributes and 2 behaviors: +```Ruby +class SomeDoggo + attr_accessor :name, :age, :has_energy + def initialize(name, age, has_energy) + @name = name + @age = age + @has_energy = has_energy + end + + def dog_tag + puts "This dog's name is #{name}." + end + + def has_birthday + self.age += 1 # created error until ".self" added + puts "Today #{name} is #{age} years old." + end + + def go_running + self.has_energy = false # created undefined error until ".self" added + end +end +``` 1. How do you create an instance of a class? +```Ruby +greg = SomeDoggo.new(Greg, 3, true) +``` 1. What questions do you still have about classes in Ruby? +Many concepts were new to me in the readings. I think I have an okay understanding of the general syntax, including the getter-setter (attr_accessor). It took a while to understand ".self" --> making sure that the instance variable NOT a new local variable was referenced + +I struggled through the "my car" exercise on launchschool so clearly I need more practice with this topic. + +Question: when creating methods in a class, what is the difference between using **"@"** and **".self"** with variables? + +(Related?) What is the difference between and **instance method** and an **accessor method**? diff --git a/day_7/10_speckled_frogs.rb b/day_7/10_speckled_frogs.rb new file mode 100644 index 000000000..2c68b341c --- /dev/null +++ b/day_7/10_speckled_frogs.rb @@ -0,0 +1,25 @@ +# Prints nursery rhyme based on starting number of frogs + +def ten_speckled_frogs(frog_qty) + loop do + if frog_qty > 2 + puts "#{frog_qty} speckled frogs sat on a log eating some most delicious bugs. +One jumped in the pool where it's nice and cool, then there were #{(frog_qty - 1)} speckled frogs.\n" + puts "" + frog_qty -= 1 + elsif frog_qty == 2 + puts puts "#{frog_qty} speckled frogs sat on a log eating some most delicious bugs.\n +One jumped in the pool where it's nice and cool, then there was #{(frog_qty - 1)} speckled frog!" + puts "" + frog_qty -= 1 + elsif frog_qty == 1 + puts puts "#{frog_qty} speckled frog sat on a log eating some most delicious bugs.\n +One jumped in the pool where it's nice and cool, then there were no more speckled frogs!" + frog_qty -= 1 + else + break + end + end +end + +ten_speckled_frogs(10) diff --git a/day_7/10_speckled_frogs_extension1.rb b/day_7/10_speckled_frogs_extension1.rb new file mode 100644 index 000000000..b9ef76289 --- /dev/null +++ b/day_7/10_speckled_frogs_extension1.rb @@ -0,0 +1,29 @@ +# Prints nursery rhyme based on starting number of frogs +# Uses gem "to_words" + +# gem install 'to_words' # Un-comment out line 4 and comment out line 5 if gem install needed +require 'to_words' + +def ten_speckled_frogs(frog_qty) + loop do + if frog_qty > 2 + puts "#{frog_qty.to_words.capitalize} speckled frogs sat on a log eating some most delicious bugs. +One jumped in the pool where it's nice and cool, then there were #{(frog_qty - 1).to_words} speckled frogs.\n" + puts "" + frog_qty -= 1 + elsif frog_qty == 2 + puts puts "#{frog_qty.to_words.capitalize} speckled frogs sat on a log eating some most delicious bugs.\n +One jumped in the pool where it's nice and cool, then there was #{(frog_qty - 1).to_words} speckled frog!" + puts "" + frog_qty -= 1 + elsif frog_qty == 1 + puts puts "#{frog_qty.to_words.capitalize} speckled frog sat on a log eating some most delicious bugs.\n +One jumped in the pool where it's nice and cool, then there were no more speckled frogs!" + frog_qty -= 1 + else + break + end + end +end + +ten_speckled_frogs(10) diff --git a/day_7/caesar_cipher.rb b/day_7/caesar_cipher.rb new file mode 100644 index 000000000..dd1958eeb --- /dev/null +++ b/day_7/caesar_cipher.rb @@ -0,0 +1,32 @@ +# Third attempt at Caesar Cipher using array indices, and modulo for wrapping +def caesar_cipher(string, shift_value) + alphabet_array = ("A".."Z").to_a + user_array = string.upcase.split("") + encoded_array = Array.new + position = 0 + remainder = 0 + user_array.each do |character| + if alphabet_array.index(character) == nil # Pass on non-alpha characters + encoded_array.push(character) + else + position = alphabet_array.index(character) + shift_value # Shift along the index of the alphabet array + # Wrapping + if position > 25 || position < 0 # indices 0-25 + remainder = position % 26 + encoded_array.push(alphabet_array[remainder]) + else + encoded_array.push(alphabet_array[position]) + end + end + end + puts encoded_array.join +end + +puts "Caesar Cipher" +puts "-------------" +print "Please enter the word(s) you want to encode: " +string = gets.chomp +print "Enter the number of characters to shift by (ex. 3 shifts A to D; -3 shifts A to X): " +shift_value = gets.chomp.to_i + +caesar_cipher(string, shift_value) diff --git a/day_7/caesar_cipher_attempt1.rb b/day_7/caesar_cipher_attempt1.rb new file mode 100644 index 000000000..8d050eafd --- /dev/null +++ b/day_7/caesar_cipher_attempt1.rb @@ -0,0 +1,30 @@ +# This program takes a user supplied string and shift value to return a +# shift cipher version of the string in upper case characters + +def encode + cipher_hash = {"A" => 0, "B" => 1, "C" => 2, "D" => 3, "E" => 4, "F" => 5 "G" => 6, "H" => 7, "I" => 8, "J" => 9, "K" => 10, "L" => 11, "M" => 12, "N" => 13, "O" => 14, "P" => 15, "Q" => 16, "R" => 17, "S" => 18, "T" => 19, "U" => 20, "V" => 21, "W" => 22, "X" => 23, "Y" => 24, "Z" => 25} + cipher_array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] + encoded_array = Array.new + user_array = $user_string.split # Creates array of individual characters + user_array.each do |a| + if ["a-zA-Z"] # check if a letter; use parentheses here? +# The crux: reassign to shifted character + a = #cipher_array[()] + encoded_array.push(a) # add shifted character + else + encoded_array.push(a) # if a non-letter character just adds as is + end + puts encoded_array.join # prints encoded string + puts "" + puts "The key to your encoded message is #{$user_shift.to_s}." + end +end + +puts "Caesar Cipher" +puts "-------------" +print "Please enter the word(s) you want to encode: " +$user_string = gets.chomp.upcase +print "Enter the number of characters to shift by (ex. 3 shifts A to D; -3 shifts A to X): " +$user_shift = gets.chomp.to_i + +# encode(user_string, user_shift) diff --git a/day_7/caesar_cipher_attempt2.rb b/day_7/caesar_cipher_attempt2.rb new file mode 100644 index 000000000..d3e957b75 --- /dev/null +++ b/day_7/caesar_cipher_attempt2.rb @@ -0,0 +1,30 @@ +# This program takes a user supplied string and shift value to return a +# shift cipher version of the string in upper case characters +$user_string = "" # Used global variables to allow for initial user interface +$user_shift = 0 + + +def encode + encoded_array = Array.new + user_array = $user_string.split("") # Creates array from string + user_array.each do |character| + if character =~ /[A-Z]/ # If the character is a letter + character = (((character.ord) + $user_shift) % 26).chr # Shifts using ASCII number and modulo to attempt to handle wrapping + encoded_array.push(character) + elsif character =~ /[^A-Z]/ # Handles spaces + encoded_array.push(character) + end + end + puts encoded_array.join # Converts shifted array into a shifted string + puts "" + puts "Note: your cipher key is #{$user_shift.to_s}" # Remind the user of the key to their caesar cipher +end + +puts "Caesar Cipher" +puts "-------------" +print "Please enter the word(s) you want to encode: " +$user_string = gets.chomp.upcase # Gets a string from the user and formats all uppercase +print "Enter the number of characters to shift by (ex. 3 shifts A to D; -3 shifts A to X): " +$user_shift = gets.chomp.to_i # Gets a number from the user and converts to an integer + +encode # runs method diff --git a/day_7/checker_board.rb b/day_7/checker_board.rb new file mode 100644 index 000000000..48e8175b2 --- /dev/null +++ b/day_7/checker_board.rb @@ -0,0 +1,41 @@ +# Program prints a checkerboard based on a size provided by the user +def checkerboard(board_size) + row_counter = board_size + while row_counter > 0 + square_counter = board_size + if row_counter.odd? == true + while square_counter > 0 + if square_counter.odd? == true + print "X" + else + print " " + end + square_counter -= 1 + end + else + while square_counter > 0 + if square_counter.odd? == true + print " " + else + print "X" + end + square_counter -= 1 + end + end + puts "" + row_counter -= 1 + end +end + +puts "This program will print a checkerboard." +puts "Black spaces are represented by 'X' and white spaces by ' '." +puts "------------------------------------------------------------" +print "What size do you want the board to be? Enter a number: " +board_size = gets.chomp.to_i +loop do + break if board_size.positive? + puts "Input error. Enter a positive integer." + board_size = gets.chomp.to_i +end + +checkerboard(board_size) diff --git a/day_7/fizzbuzz.rb b/day_7/fizzbuzz.rb new file mode 100644 index 000000000..a884874bb --- /dev/null +++ b/day_7/fizzbuzz.rb @@ -0,0 +1,25 @@ +# Program that prints something for each number from 1 to 100 +# following several rules + +def fizz_buzz(n) + # Create array of integers 1 to n + num_array = (1..n).to_a + # Iterate through the elements of the array + num_array.each do |a| + # For any number that is a multiple of both 3 and 5, print 'FizzBuzz' + if (a % 3) == 0 && (a % 5) == 0 + print "FizzBuzz, " +# For any number that is a multiple of 3, print 'Fizz' + elsif (a % 3) == 0 && (a % 5) != 0 + print "Fizz, " +# For any number that is a multiple of 5, print 'Buzz' + elsif (a % 3) != 0 && (a % 5) == 0 + print "Buzz, " +# For all other numbers, print the number + else + print "#{a}, " + end + end +end + +fizz_buzz(100) diff --git a/day_7/high_level.md b/day_7/high_level.md new file mode 100644 index 000000000..7b116775a --- /dev/null +++ b/day_7/high_level.md @@ -0,0 +1,62 @@ +# Ceasar Cipher - High Level Notes + +* _A Caesar Cipher works by shifting the alphabet by a defined number of letters down the alphabet_ +* _The program must be able to take any string and encode it based on a user-provided shift value_ + +## The plan + +The program will get string input and an integer "shift value" from the user. + +The method will format the string as uppercase and split it into an array. + +Next, the method will iterate through the array and use the shift value to target a shifted character based on an array of uppercase letters (A-Z). It will put each shifted letter into a new array. The program will not alter spaces or other non-alpha characters in the string based on absence from the A-Z array. + +Finally, the shifted array elements will be joined into a string and will be displayed to the user. + + +### Expected difficulty + +The crux of this program is figuring out how to handle shifts that go beyond the values of the alphabet(_wrapping_ e.g. below A/1 and above Z/26). Is using an array or a hash the best way to shift and replace the characters? + +After doing light spoiler-free research, considering if there is a useful Ruby method to convert a string character to its ASCII number and modifying it by the shift. This leaves the issue of _wrapping_ unresolved. See "caesar_cipher_attempt2.rb" for a partial solution that cannot handle wrapping. + +### Notes while writing program + +I got stuck when it came to working with the array made from the user string. How can I connect to identical characters in a separate "alphabet" array (use the index positions to shift the letters)? + +1. This led me to explore the methods required to convert alpha characters to ASCII, modify, and replace. + +1. I passed on non-alpha characters using conditional branching. + +1. I encountered many problems with my code, leading me to look up methods such as .ord, .chr, .each_char + +1. I got stuck for a long time on trying to use my block variable "letter" in an if-else block within iteration through the user's string's characters: + +```ruby +def caesar_cipher(string, shift_value) + alphabet_array = ["A".."Z"].to_a + encoded_array = Array.new + string.each_char do |letter| + if letter == " " # =~ /[^A-Z]/ # Why isn't letter appearing as a variable in Atom??? + encoded_array.push(" ") + else + letter.upcase + original_position = alphabet_array.find_index( letter ) + new_position = ( original_position + shift_value ) % 26 # Modulo 26 to handle wrapping? + encoded_array.push( alphabet_array[new_position] ) + end + end + puts encoded_array.join +end + +caesar_cipher("abc xyz", 1) +``` +**Then I found an error of [] versus ():** +```ruby +alphabet_array = ("A".."Z").to_a +``` + +1. Declaring variables at the beginning of the method led to the program running correctly. + +### Additional note: +When one solution didn't work out, I started again from scratch. I realize that I should have used git to document these changes.