diff --git a/ch09-writing-your-own-methods/ask.rb b/ch09-writing-your-own-methods/ask.rb index 01716eb35..36accc9a2 100644 --- a/ch09-writing-your-own-methods/ask.rb +++ b/ch09-writing-your-own-methods/ask.rb @@ -1,3 +1,30 @@ -def ask question - # your code here -end \ No newline at end of file +def ask(question) + while true + puts question + reply = gets.chomp.downcase + if reply == "yes" + return true + elsif reply == "no" + return false + end + puts "Please answer 'yes' or 'no'" + end +end + +ask "Do you like eating tacos?" + + +=begin +ask "Do you like eating burritos?" +wets_bed = ask "Do you wet the bed?" +ask "Do you like eating chimichangas?" +ask "Do you like eating sopapillas?" +puts "Just a few more questions..." +ask "Do you like eating drinking horchata?" +ask "Do you like eating flautas?" +puts +puts "DEBRIEFING:" +puts "Thank you for" +puts +puts wets_bed +=end diff --git a/ch09-writing-your-own-methods/old_school_roman_numerals.rb b/ch09-writing-your-own-methods/old_school_roman_numerals.rb index ca6589f2d..5b19c148b 100644 --- a/ch09-writing-your-own-methods/old_school_roman_numerals.rb +++ b/ch09-writing-your-own-methods/old_school_roman_numerals.rb @@ -1,3 +1,16 @@ -def old_roman_numeral num - # your code here -end \ No newline at end of file +def old_roman_numeral(number) + num = "" + num = num + "M" * (number / 1000) + num = num + "D" * (number % 1000 / 500) + num = num + "C" * (number % 500 / 100) + num = num + "L" * (number % 100 / 50) + num = num + "X" * (number % 50 / 10) + num = num + "V" * (number % 10 / 5) + num = num + "I" * (number % 5 / 1) +end + +puts old_roman_numeral(4) +puts old_roman_numeral(5) +puts old_roman_numeral(10) +puts old_roman_numeral(19) +puts old_roman_numeral(22) diff --git a/ch09-writing-your-own-methods/roman_numerals.rb b/ch09-writing-your-own-methods/roman_numerals.rb index 5c93b59ac..d77c1e3cf 100644 --- a/ch09-writing-your-own-methods/roman_numerals.rb +++ b/ch09-writing-your-own-methods/roman_numerals.rb @@ -1,3 +1,46 @@ -def roman_numeral num - # your code here -end \ No newline at end of file +def roman_numeral(num) + thousands = (num / 1000) + hundreds = (num % 1000 / 100) + tens = (num % 100 / 10) + ones = (num % 10) + roman = "M" * thousands + + if hundreds == 9 + roman += "CM" + elsif hundreds == 4 + roman += "CD" + else + roman += "D" * (num % 1000 / 500) + roman += "C" * (num % 500 / 100) + end + if tens == 9 + roman += "XC" + elsif tens == 4 + roman += "XL" + else + roman += "L" * (num % 100 / 50) + roman += "X" * (num % 50 / 10) + end + if ones == 9 + roman += "IX" + elsif ones == 4 + roman += "IV" + else + roman += "V" * (num % 10 / 5) + roman += "I" * (num % 5 / 1) + end + roman +end + +puts roman_numeral(1) +puts roman_numeral(2) +puts roman_numeral(3) +puts roman_numeral(4) +puts roman_numeral(5) +puts roman_numeral(6) +puts roman_numeral(7) +puts roman_numeral(8) +puts roman_numeral(9) +puts roman_numeral(10) +puts roman_numeral(14) +puts roman_numeral(19) diff --git a/ch10-nothing-new/dictionary_sort.rb b/ch10-nothing-new/dictionary_sort.rb index c9893d0fd..1980a2e51 100644 --- a/ch10-nothing-new/dictionary_sort.rb +++ b/ch10-nothing-new/dictionary_sort.rb @@ -1,3 +1,22 @@ -def dictionary_sort arr - # your code here -end \ No newline at end of file +def dictionary_sort(arr) + rec_sort_dic arr, [] +end +def rec_sort_dic(unsorted, sorted) + if unsorted.length <= 0 + return sorted + end + smallest = unsorted.pop + still_unsorted = [] + unsorted.each do |tested| + if tested.downcase < smallest.downcase + still_unsorted.push smallest + smallest = tested + else + still_unsorted.push tested + end + end + sorted.push smallest + rec_sort_dic(still_unsorted, sorted) +end + +puts(dictionary_sort(["zebra", "cheetah", "giraffe", "cougar", "leopard", "elephant"])) diff --git a/ch10-nothing-new/english_number.rb b/ch10-nothing-new/english_number.rb index c0129bc4e..23d76ced4 100644 --- a/ch10-nothing-new/english_number.rb +++ b/ch10-nothing-new/english_number.rb @@ -1,3 +1,66 @@ -def english_number number - # your code here +def english_number(num) + if num < 0 + return "Please enter a positive number." + end + if num == 0 + return "zero" + end + num_string = "" + ones = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"] + tens = ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] + teenagers = ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] + zillions = [["hundred", 2], ["thousand", 3], ["million", 6], ["billion", 9], ["trillion", 12], + ["quadrillion", 15], ["quintillion", 18], ["sextillion", 21], ["septillion", 24], + ["octillion", 27], ["nonillion", 30], ["decillion", 33], ["undecillion", 36], + ["duodecillion", 39], ["tredecillion", 42], ["quattuordecillion", 45], + ["quindecillion", 48], ["sexdecillion", 51], ["septendecillion", 54], + ["octodecillion", 57], ["novemdecillion", 60], ["vigintillion", 63], ["googol", 100]] + left = num + + while zillions.length > 0 + zil_pair = zillions.pop + zil_name = zil_pair[0] + zil_base = 10 ** zil_pair[1] + write = left / zil_base + left -= write ** zil_base + if write > 0 + prefix = english_number write + num_string += prefix + " " + zil_name + if left > 0 + num_string += " " + end + end + end + write = left / 10 + left -= write * 10 + if write > 0 + if write == 1 && left > 0 + num_string += teenagers[left - 1] + left = 0 + else + num_string += tens[write - 1] + end + if left > 0 + num_string += "-" + end + end + write = left + left = 0 + if write > 0 + num_string += ones[write - 1] + end + num_string end + +puts english_number(1) +puts english_number(2) +puts english_number(3) +puts english_number(4) +puts english_number(5) +puts english_number(6) +puts english_number(7) +puts english_number(8) +puts english_number(9) +puts english_number(10) +puts english_number(222222) +puts english_number(33333) diff --git a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb index 801de24bd..6cac38c16 100644 --- a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb +++ b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb @@ -1 +1,13 @@ -# your code here \ No newline at end of file +num_at_start = 99 +num_now = num_at_start +while num_now > 2 + puts "#{english_number(num_now).capitalize} bottles of beer on the wall, #{english_number(num_now)} bottles of beer!" + num_now -= 1 + puts "Take on down, pass it around, #{english_number(num_now)} bottles of beer on the wall!" +end +puts """ + Two bottles of beer on the wall, two bottles of beer! + Take one down, pass it around, one bottle of beer on the wall! + One bottle of beer on the wall, one bottle of beer! + Take one dow, pass it around, no more bottles of beer on the wall! + """ diff --git a/ch10-nothing-new/shuffle.rb b/ch10-nothing-new/shuffle.rb index a486ad94c..f2257cc5a 100644 --- a/ch10-nothing-new/shuffle.rb +++ b/ch10-nothing-new/shuffle.rb @@ -1,3 +1,28 @@ -def shuffle arr - # your code here -end \ No newline at end of file +# long way +def shuffle(arr) + shuff = [] + while arr.length > 0 + rand_index = rand(arr.length) # Randomly pick an element + curr_index = 0 + new_arr = [] + arr.each do |item| + if curr_index == rand_index + shuff.push item + else + new_arr.push item + end + curr_index += 1 + end + arr = new_arr + end + shuff +end + +# short way +=begin +def shuffle(arr) + arr.sort_by{rand} +end +=end +animals = ["zebra", "donkey", "monkey", "tarsier", "platypus", "anteater", "koala"] +puts shuffle(animals) diff --git a/ch10-nothing-new/sort.rb b/ch10-nothing-new/sort.rb index 44c6deb58..78efeb463 100644 --- a/ch10-nothing-new/sort.rb +++ b/ch10-nothing-new/sort.rb @@ -1,3 +1,38 @@ -def sort arr - # your code here -end \ No newline at end of file +# long way +def sort(arr) + rec_sort arr, [] +end + +def rec_sort(unsorted, sorted) + if unsorted.length <= 0 + return sorted + end + smallest = unsorted.pop # starting point + still_unsorted = [] + unsorted.each do |tested| + if tested < smallest # comparison + still_unsorted.push smallest # add for further resorting later + smallest = tested # reassign value for tested to be compared with next tested value + else + still_unsorted.push tested # in this case tested is larger + end + end + sorted.push smallest + rec_sort(still_unsorted, sorted) +end + +puts (sort(["can", "feel","singing", "like", "a", "can"])) +animals = ["zebra", "donkey", "monkey", "tarsier", "platypus", "anteater", "koala"] +puts +puts sort(animals) + +# short way +=begin +def sort(arr) + return arr if arr.length <= 1 # breaks the loop + mid_point = arr.pop # acts as the starting point for comparisons + smaller = arr.select {|x| x < mid_point} + bigger = arr.select {|x| x > mid_point} + sort(smaller) + [mid_point] + sort(bigger) +end +=end diff --git a/ch11-reading-and-writing/build_a_better_playlist.rb b/ch11-reading-and-writing/build_a_better_playlist.rb index 3b31bd241..cda96c590 100644 --- a/ch11-reading-and-writing/build_a_better_playlist.rb +++ b/ch11-reading-and-writing/build_a_better_playlist.rb @@ -1,3 +1,30 @@ -def music_shuffle filenames - # your code here +def music_shuffle(filenames) + filenames = filenames.sort + length = filenames.length + 2.times do + l_idx = 0 + r_idx = length / 2 + shuff = [] + while shuff.length < length + if shuff.length % 2 == 0 + shuff.push(filenames[r_idx]) + r_idx += 1 + else + shuff.push(filenames[l_idx]) + l_idx += 1 + end + end + filenames = shuff + end + arr = [] + cut = rand(length) + idx = 0 + while idx < length + arr.push(filenames[(idx + cut) % length]) + idx += 1 + end + arr end + +songs = ["aa/bbb", "aa/ccc", "aa/ddd", "AAA/xxxx", "AA/yyyy", "AAA/zzzz", "foo/bar"] +puts music_shuffle(songs) diff --git a/ch11-reading-and-writing/build_your_own_playlist.rb b/ch11-reading-and-writing/build_your_own_playlist.rb index 801de24bd..f96f1e603 100644 --- a/ch11-reading-and-writing/build_your_own_playlist.rb +++ b/ch11-reading-and-writing/build_your_own_playlist.rb @@ -1 +1,7 @@ -# your code here \ No newline at end of file +all_oggs = shuffle(Dir["**/*.ogg"]) +File.open "playlist.m3u", "w" do |f| + all_oggs.each do |ogg| + f.write ogg + "\n" + end +end +puts "Finished!" diff --git a/ch12-new-classes-of-objects/birthday_helper.rb b/ch12-new-classes-of-objects/birthday_helper.rb index 801de24bd..df3989cf3 100644 --- a/ch12-new-classes-of-objects/birthday_helper.rb +++ b/ch12-new-classes-of-objects/birthday_helper.rb @@ -1 +1,21 @@ -# your code here \ No newline at end of file +birth_dates = {} +File.read("birthdates.txt").each_line do |line| + line = line.chomp + first_comma = 0 + while line[first_comma] != "," && + first_comma < line.length + first_comma += 1 + end + name = line[0..(first_comma - 1)] + date = line[-12..-1] + birth_dates[name] = date + end + +puts "Who's birthday would you like to know?" +name = $stdin.gets.chomp +date = birth_dates[name] +if date == nil + puts "Sorry, I don't know that one." +else + puts date[0..5] +end diff --git a/ch12-new-classes-of-objects/happy_birthday.rb b/ch12-new-classes-of-objects/happy_birthday.rb index 801de24bd..78c75d6ec 100644 --- a/ch12-new-classes-of-objects/happy_birthday.rb +++ b/ch12-new-classes-of-objects/happy_birthday.rb @@ -1 +1,13 @@ -# your code here \ No newline at end of file +puts "Only enter integers please" +puts "What year were you born?" +year = gets.chomp +puts "What month were you born?" +month = gets.chomp +puts "What date was the day you were born?" +day = gets.chomp + +age_result = Time.now - Time.local(year, month, day) +age_in_years = age_result / (60 * 60 * 24 *365) +puts "Just in case you have forgotten, I would like to remind you" +puts "that you are #{age_in_years.floor} years old!" +puts "SPANK!\n" * age_in_years diff --git a/ch12-new-classes-of-objects/one_billion_seconds.rb b/ch12-new-classes-of-objects/one_billion_seconds.rb index 801de24bd..72affcad9 100644 --- a/ch12-new-classes-of-objects/one_billion_seconds.rb +++ b/ch12-new-classes-of-objects/one_billion_seconds.rb @@ -1 +1,2 @@ -# your code here \ No newline at end of file +age = Time.now - Time.local(1985, 6, 5, 14, 00) +puts "I am #{age} seconds old!" diff --git a/ch13-creating-new-classes/extend_built_in_classes.rb b/ch13-creating-new-classes/extend_built_in_classes.rb index c3e793933..b78ae990f 100644 --- a/ch13-creating-new-classes/extend_built_in_classes.rb +++ b/ch13-creating-new-classes/extend_built_in_classes.rb @@ -1,3 +1,22 @@ class Integer - # your code here -end \ No newline at end of file + def factorial + if self <= 1 + 1 + else + self * (self - 1).factorial + end + end + def to_roman + roman = "" + roman += "M" * (self / 1000) + roman += "D" * (self % 1000 / 500) + roman += "C" * (self % 500 / 100) + roman += "L" * (self % 100 / 50) + roman += "X" * (self % 50 / 10) + roman += "V" * (self % 10 / 5) + roman += "I" * (self % 5 / 1) + end +end + +puts 7.factorial +puts 73.to_roman diff --git a/ch13-creating-new-classes/interactive_baby_dragon.rb b/ch13-creating-new-classes/interactive_baby_dragon.rb index 801de24bd..e92012585 100644 --- a/ch13-creating-new-classes/interactive_baby_dragon.rb +++ b/ch13-creating-new-classes/interactive_baby_dragon.rb @@ -1 +1,23 @@ -# your code here \ No newline at end of file +puts "What would you like to name our baby dragon?" +name = $stdin.gets.chomp +pet = Dragon.new(name) +while true + puts + puts "Commands: feed, toss, walk, rock, puts to bed, exit" + command = $stdin.gets.chomp + if command == "exit" + exit + elsif command == "feed" + pet.feed + elsif command == "toss" + pet.toss + elsif command == "walk" + pet.walk + elsif command == "rock" + pet.rock + elsif command == "put to bed" + pet.put to bed + else + puts "Huh? Please type one of the commands." + end +end diff --git a/ch13-creating-new-classes/orange_tree.rb b/ch13-creating-new-classes/orange_tree.rb index 025d08907..0682b7b8e 100644 --- a/ch13-creating-new-classes/orange_tree.rb +++ b/ch13-creating-new-classes/orange_tree.rb @@ -1,11 +1,80 @@ -# in order to pass the rspec please follow the below rates of growth, orange production and age of death. -# have your OrangeTree grow by 0.4 per year. -# have it produce no oranges in its first 5 years -# starting in its sixth year have it produce oranges at a rate of (height * 15 - 25) per year. -# have the tree die after 25 years. -# check out the rspec spec/ch13/orange_tree_spec.rb to see what strings we're looking for in the responses. +=begin +in order to pass the rspec please follow the below rates of growth, orange + production and age of death. +have your OrangeTree grow by 0.4 per year. +have it produce no oranges in its first 5 years starting in its sixth year + have it produce oranges at a rate of (height * 15 - 25) per year. +have the tree die after 25 years. +check out the rspec spec/ch13/orange_tree_spec.rb to see what strings +we're looking for in the responses. +=end class OrangeTree - # your code here + def initialize + @height = 0 + @orange_count = 0 + @alive = true + end + def height + if @alive + @height + else + "A dead tree is not very tall. :(" + end + end + def count_the_oranges + if @alive + @orange_count + else + "A dead tree has no oranges. :(" + end + end + def one_year_passes + if @alive + @height += 0.4 + @orange_count = 0 + if @height > 10 && rand(2) > 0 + @alive = false + "Oh, no! The tree is too old, and has died. :(" + elsif @height > 2 + @orange_count = (@height * 15 - 25).to_i + "This year your tree grew to #{@height}m tall," + + " and produced #{@orange_count} oranges." + else + "This year your tree grew to #{@height}m tall," + + " but is still too young to bear fruit." + end + else + "A year later, the tree is still dead. :(" + end + end + def pick_an_orange + if @alive + if @orange_count > 0 + @orange_count -= 1 + "You pick a juicy, delicious orange!" + else + "You search every branch, but find no oranges." + end + else + "A dead tree has nothing to pick. :(" + end + end end +ot = OrangeTree.new +23.times do + ot.one_year_passes +end + +puts(ot.one_year_passes) +puts(ot.count_the_oranges) +puts(ot.height) +puts(ot.one_year_passes) +puts(ot.one_year_passes) +puts(ot.one_year_passes) +puts(ot.one_year_passes) +puts(ot.one_year_passes) +puts(ot.height) +puts(ot.count_the_oranges) +puts(ot.pick_an_orange) diff --git a/ch13-creating-new-classes/slightly_different_baby_dragon.rb b/ch13-creating-new-classes/slightly_different_baby_dragon.rb new file mode 100644 index 000000000..af1801514 --- /dev/null +++ b/ch13-creating-new-classes/slightly_different_baby_dragon.rb @@ -0,0 +1,117 @@ +class Dragon + + def initialize(name, gender) + @name = name + if (gender == "Male" || gender == "male" || gender == "M" || gender == "m") + @gender = "He" + elsif (gender == "Female" || gender == "female" || gender == "F" || gender == "f") + @gender = "She" + else + @gender = name + end + @sleep = false + @stuff_in_belly = 10 + @stuff_in_intestine = 0 + + puts "#{name} is born." + end + + def feed + puts "You feed #{@name}." + @stuff_in_belly = 10 + passage_of_time + end + + def walk + puts "You walk #{@name}." + @stuff_in_intestine = 0 + passage_of_time + end + + def put_to_bed + puts "You put #{@name} to bed." + @asleep = true + 3.times do + if @asleep + passage_of_time + end + if @asleep + puts "#{@name} snores, filling the room with smoke." + end + end + if @asleep + @asleep = false + puts "#{@name} wakes up slowly." + end + end + + def toss + puts "You toss #{@name} into the air." + puts "#{@gender} giggles, which singes your eyebrows." + passage_of_time + end + + def rock + puts "You rock #{@name} gently." + @asleep = true + puts "#{@gender} briefly dozes off..." + passage_of_time + if @asleep + @asleep = false + puts "...but wakes when you stop." + end + end + + private + + def hungry? + @stuff_in_belly <= 2 + end + + def poopy? + @stuff_in_intestine >= 8 + end + + def passage_of_time + if @stuff_in_belly > 0 + @stuff_in_belly -= 1 + @stuff_in_intestine += 1 + else + if @asleep + @asleep = false + puts "#{@gender} wakes up sudeenly!" + end + puts "#{@name} is starving! In desperation, #{@gender} ATE you!" + exit + end + if @stuff_in_intestine >= 10 + @stuff_in_belly = 0 + puts "Whoops! #{@name} had an accident..." + end + if hungry? + if @asleep + @asleep = false + puts "#{@gender} wakes up suddenly!" + end + puts "#{@name}'s stomach grumbles..." + end + if poopy? + if @asleep + @asleep = false + puts "#{@gender} wakes up suddenly!" + end + puts "#{@name} does the potty dance..." + end + end +end + +pet = Dragon.new "Yiwei", "Female" +pet.feed +pet.toss +pet.walk +pet.put_to_bed +pet.rock +pet.put_to_bed +pet.put_to_bed +pet.put_to_bed +pet.put_to_bed diff --git a/ch14-blocks-and-procs/better_program_logger.rb b/ch14-blocks-and-procs/better_program_logger.rb index 0e2e18d57..9e6e87a41 100644 --- a/ch14-blocks-and-procs/better_program_logger.rb +++ b/ch14-blocks-and-procs/better_program_logger.rb @@ -1,3 +1,19 @@ -def log desc, &block - # your code here -end \ No newline at end of file +$logger_depth = 0 +def log(desc, &block) + prefix = " "*$logger_depth + puts "#{prefix}Beginning \"#{desc}\"..." + $logger_depth += 1 + result = block.call + $logger_depth -= 1 + puts "#{prefix}...\"#{desc}\" finished, returning: #{result.to_s}" +end +log "outer block" do + log "teeny-tiny block" do + "lOtS oF lOVe".downcase + end + 7 * 3 * 2 +end +log "yet another block" do + "!doof naidnI evol I".reverse +end +"0" == "0" diff --git a/ch14-blocks-and-procs/even_better_profiling.rb b/ch14-blocks-and-procs/even_better_profiling.rb index b01b78fd8..d5a686230 100644 --- a/ch14-blocks-and-procs/even_better_profiling.rb +++ b/ch14-blocks-and-procs/even_better_profiling.rb @@ -1,3 +1,11 @@ -def profile block_description, &block - # your code here -end \ No newline at end of file +def profile(block_description, &block) + profiling_on = false + if profiling_on + start_time = Time.new + block.call + duration = Time.new - start_time + puts "#{block_description}: #{duration} seconds" + else + block.call + end +end diff --git a/ch14-blocks-and-procs/grandfather_clock.rb b/ch14-blocks-and-procs/grandfather_clock.rb index 916f6d354..ccf1edcc7 100644 --- a/ch14-blocks-and-procs/grandfather_clock.rb +++ b/ch14-blocks-and-procs/grandfather_clock.rb @@ -1,3 +1,16 @@ -def grandfather_clock &block - # your code here -end \ No newline at end of file + +def grandfather_clock(&block) + hour = Time.new.hour + if hour >= 13 + hour -= 12 + end + if hour == 0 + hour = 12 + end + hour.times do + block.call + end +end +grandfather_clock do + puts "DONG!" +end diff --git a/ch14-blocks-and-procs/program_logger.rb b/ch14-blocks-and-procs/program_logger.rb index 0e2e18d57..dabed7e60 100644 --- a/ch14-blocks-and-procs/program_logger.rb +++ b/ch14-blocks-and-procs/program_logger.rb @@ -1,3 +1,14 @@ -def log desc, &block - # your code here -end \ No newline at end of file +def program_log(desc, &block) + puts "Beginning \"#{desc}\"..." + result = block.call + puts "...\"#{desc} finished, returning: #{result.to_s}" +end +program_log "outer block" do + program_log "some little block" do + 1**1 + 2**2 + end + program_log "yet another block" do + "!doof iahT ekil I".reverse + end + "0" == 0 +end