diff --git a/ch08-arrays.rb b/ch08-arrays.rb new file mode 100644 index 000000000..ebe66878a --- /dev/null +++ b/ch08-arrays.rb @@ -0,0 +1,24 @@ +# Type as many words as we want (one word per line), continuing until we press Enter on an empty line +# Repeat the words back to us in alphabetical order. +# Test program thoroughly. + +words = [] +puts "Hello, why don't you type some lines? Enter one word per line. When you get fed up, press Enter on an empty line." + +userInputEmpty = false + +while userInputEmpty == false + + word = gets.chomp + + if word != "" + words.push word + puts "How about another word? Leave empty if you're done" + + else + userInputEmpty = true + end +end + +puts "And here is a lovely alphabetical list of your words!" +puts words.sort diff --git a/ch09-writing-your-own-methods/ask.rb b/ch09-writing-your-own-methods/ask.rb index 01716eb35..23e9a058d 100644 --- a/ch09-writing-your-own-methods/ask.rb +++ b/ch09-writing-your-own-methods/ask.rb @@ -1,3 +1,39 @@ def ask question - # your code here -end \ No newline at end of file + while true + puts question + reply = gets.chomp.downcase + + if (reply == "yes" || reply == "no") + if reply == "yes" + return true + else + return false + end + break + else + puts 'Please answer "yes" or "no".' + + end + end + + answer +end + +puts "Hello, and thank you for participating." +puts + +ask "Do you like eating tacos?" +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 drinking horchata?" +ask "Do you like eating flautas?" + +puts +puts "DEBRIEFING" +puts "Thanks for taking part. Actually it wasn't about mexican food; it was about bed wetting." +puts +puts "And your answer to that question was..." +puts wets_bed 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..7153aa0c2 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,48 @@ +# Write a method that when passed an integer between 1 and 3000 (or so) +# returns a string containing the proper old-school Roman numeral. + +# M = 1000 +# D = 500 +# C = 100 +# L = 50 +# X = 10 +# V = 5 +# I = 1 + +# Hint: use the integer division and modulus methods + +# How many times does each of those roman numerals factor into numberRequested? + +# Example: 1759 + +# 1 x 1000 = M +# 1 x 500 = D +# 2 x 100 = CC +# 1 x 50 = L +# 0 x 10 = no Xs +# 1 x 5 = V +# 4 x 1 = IIII + +# MDCCLVIIII + +# How many times does 1,000 go into it? Put that many Ms. +# How many times does 500 go into the remainder? Put that many Ds. +# How many times does 100 go into the remainder? Put that many Cs. +# How many times does 50 go into the remainder? Put that many Ls. +# How many times does 10 go into the remainder? Put that many Xs. +# How many times does 5 go into the remainder? Put that many Vs. +# How many times does 1 go into the remainder? Put that many Is. + def old_roman_numeral num - # your code here -end \ No newline at end of file + + numberMs = "M" * (num / 1000) + numberDs = "D" * ((num % 1000) / 500) + numberCs = "C" * ((num % 500) / 100) + numberLs = "L" * ((num % 100) / 50) + numberXs = "X" * ((num % 50) / 10) + numberVs = "V" * ((num % 10) / 5) + numberIs = "I" * ((num % 5) / 1) + + return numberMs + numberDs + numberCs + numberLs + numberXs + numberVs + numberIs + +end diff --git a/ch09-writing-your-own-methods/roman_numerals.rb b/ch09-writing-your-own-methods/roman_numerals.rb index 5c93b59ac..d8a91d9db 100644 --- a/ch09-writing-your-own-methods/roman_numerals.rb +++ b/ch09-writing-your-own-methods/roman_numerals.rb @@ -1,3 +1,54 @@ +# M = 1000 +# D = 500 +# C = 100 +# L = 50 +# X = 10 +# V = 5 +# I = 1 + def roman_numeral num - # your code here -end \ No newline at end of file + + number1000s = (num / 1000) + number100s = (num % 1000) / 100 + number10s = (num % 100) / 10 + number1s = (num % 10) / 1 + + numberDs = (num % 1000) / 500 + numberCs = (num % 500) / 100 + numberLs = (num % 100) / 50 + numberXs = (num % 50) / 10 + numberVs = (num % 10) / 5 + numberIs = (num % 5) / 1 + + result = "M" * number1000s + + if number100s == 9 + result = result + "CM" + elsif number100s == 4 + result = result + "CD" + else + result = result + "D" * numberDs + result = result + "C" * numberCs + end + + if number10s == 9 + result = result + "XC" + elsif number10s == 4 + result = result + "XL" + else + result = result + "L" * numberLs + result = result + "X" * numberXs + end + + if number1s == 9 + result = result + "IX" + elsif number1s == 4 + result = result + "IV" + else + result = result + "V" * numberVs + result = result + "I" * numberIs + end + + result + +end diff --git a/ch10-nothing-new/dictionary_sort.rb b/ch10-nothing-new/dictionary_sort.rb index c9893d0fd..eadc70253 100644 --- a/ch10-nothing-new/dictionary_sort.rb +++ b/ch10-nothing-new/dictionary_sort.rb @@ -1,3 +1,42 @@ +# Okay how do we solve this in English? +# For the purpose of comparison, we should just downcase everything +# But if it were capitalised to begin with, it ought to remain so + def dictionary_sort arr - # your code here -end \ No newline at end of file + recursive_sort arr, [] +end + +def recursive_sort unsorted_array, sorted_array + + # If the unsorted array has no items in it, return the sorted array + if unsorted_array.length <= 0 + return sorted_array + end + + # Remove the last word from the unsorted array and put it into the variable smallest + smallest = unsorted_array.pop + + # Create a new array called still_unsorted to hold all the other words + still_unsorted = [] + + # For each word in the unsorted array, see if it's smaller than the 'smallest' word that you took earlier + # If it is, put the smallest word back into the array, and replace 'smallest' with this new word + # If word is not smaller than the smallest, then push this word into the still unsorted array + + unsorted_array.each do | word | + + if word.downcase < smallest.downcase + still_unsorted.push smallest + smallest = word + else + still_unsorted.push word + end + end + + # Put the smallest word into the sorted array + sorted_array.push smallest + + # Now call the same recursive sort method to sort out the still_unsorted words + recursive_sort still_unsorted, sorted_array + +end diff --git a/ch10-nothing-new/english_number.rb b/ch10-nothing-new/english_number.rb index c0129bc4e..378814c7c 100644 --- a/ch10-nothing-new/english_number.rb +++ b/ch10-nothing-new/english_number.rb @@ -1,3 +1,90 @@ def english_number number - # your code here + if number < 0 + return "Please enter a number that isn't negative." + end + + if number == 0 + return "zero" + end + + num_string = "" + + ones_place = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] + tens_place = ['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], + ['sexdicillion', 51], + ['septendecillion', 54], + ['octodecillion', 57], + ['novembdecillion', 60], + ['vigintillion', 63], + ['googol', 100]] + + left = number + + while zillions.length > 0 + zil_pair = zillions.pop + zil_name = zil_pair[0] + zil_base = 10 ** zil_pair[1] + write = left/zil_base + left = left - write*zil_base + + if write > 0 + prefix = english_number write + num_string = num_string + prefix + " " + zil_name + if left > 0 + num_string = num_string + " " + end + end + end + + write = left/10 + left = left - write*10 + + if write > 0 + if ((write == 1) and (left > 0)) + num_string = num_string + teenagers[left-1] + left = 0 + else + num_string = num_string + tens_place[write-1] + end + + if left > 0 + num_string = num_string + "-" + end + end + + write = left + left = 0 + + if write > 0 + num_string = num_string + ones_place[write-1] + end + + num_string + end + +# puts english_number 937234827364876238423423487686234 +# puts english_number 234987234982398798423 +# puts english_number 23432 +puts english_number 99 +puts english_number 234 +puts english_number 109238745102938560129834709285360238475982374561034 +# puts english_number 9898176572634765762999987987 diff --git a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb index 801de24bd..d9cb3aa2f 100644 --- a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb +++ b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb @@ -1 +1,98 @@ -# your code here \ No newline at end of file +def english_number number + if number < 0 + return "Please enter a number that isn't negative." + end + + if number == 0 + return "zero" + end + + num_string = "" + + ones_place = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] + tens_place = ['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], + ['sexdicillion', 51], + ['septendecillion', 54], + ['octodecillion', 57], + ['novembdecillion', 60], + ['vigintillion', 63], + ['googol', 100]] + + left = number + + while zillions.length > 0 + zil_pair = zillions.pop + zil_name = zil_pair[0] + zil_base = 10 ** zil_pair[1] + write = left/zil_base + left = left - write*zil_base + + if write > 0 + prefix = english_number write + num_string = num_string + prefix + " " + zil_name + if left > 0 + num_string = num_string + " " + end + end + end + + write = left/10 + left = left - write*10 + + if write > 0 + if ((write == 1) and (left > 0)) + num_string = num_string + teenagers[left-1] + left = 0 + else + num_string = num_string + tens_place[write-1] + end + + if left > 0 + num_string = num_string + "-" + end + end + + write = left + left = 0 + + if write > 0 + num_string = num_string + ones_place[write-1] + end + + num_string + +end + +def bottles_of_beer num + while num > 0 + english_num = english_number num + puts english_num.capitalize + " bottles of beer on the wall, " + english_num + " bottles of beer!" + english_num = english_number num-1 + num -= 1 + if num == 0 + puts "Take one down, pass it around, no more bottles of beer on the wall" + else + puts "Take one down, pass it around, " + english_num + " bottles of beer on the wall" + end + end +end + +bottles_of_beer 99 diff --git a/ch10-nothing-new/shuffle.rb b/ch10-nothing-new/shuffle.rb index a486ad94c..eab10598a 100644 --- a/ch10-nothing-new/shuffle.rb +++ b/ch10-nothing-new/shuffle.rb @@ -1,3 +1,44 @@ +# How would I shuffle an array in English? +# Take a random item from the given array and put it in the new array +# Keep going until all the items have moved from the given array into the new array + def shuffle arr - # your code here -end \ No newline at end of file + recursive_shuffle arr, [] +end + +def recursive_shuffle original_array, shuffled_array + + if original_array.length <= 0 + return shuffled_array + end + + # Remove the last item from the original array + randomWord = original_array.pop + + # Insert it in a random place in the shuffled array + shuffled_array.insert(rand(shuffled_array.length+1), randomWord) + + # Call the method again until all the elements have been shuffled + recursive_shuffle original_array, shuffled_array +end + + +#def shuffle arr # Chris Pine's shuffle method +# shuf = [] +# while arr.length > 0 +# rand_index = rand(arr.length) +# curr_index = 0 +# new_arr = [] +# +# arr.each do |item| +# if curr_index == rand_index +# shuf.push item +# else +# new_arr.push item +# end +# curr_index += 1 +# end +# arr = new_arr +# end +# shuf +#end diff --git a/ch10-nothing-new/sort.rb b/ch10-nothing-new/sort.rb index 44c6deb58..67768c8c4 100644 --- a/ch10-nothing-new/sort.rb +++ b/ch10-nothing-new/sort.rb @@ -1,3 +1,47 @@ +# Which of two words comes first in the dictionary (using <) +# Keep a list of already-sorted words, the other is a list of still-unsorted words +#Take our list of words, find the smallest word (that would come first in the dictionary) +# and stick it at the end of the alread-sorted list +# All of the other words go into the still unsorted list +# Then do the same thing still using the unsrted list instead of your original listFind the msallest words +# Move it to the sorted list +# Move the rest to the unsorted list +# Keep going until your still-unsorted list is empty + def sort arr - # your code here -end \ No newline at end of file + recursive_sort arr, [] +end + +def recursive_sort unsorted_array, sorted_array + + # If the unsorted array has no items in it, return the sorted array + if unsorted_array.length <= 0 + return sorted_array + end + + # Remove the last word from the unsorted array and put it into the variable smallest + smallest = unsorted_array.pop + + # Create a new array called still_unsorted to hold all the other words + still_unsorted = [] + + # For each word in the unsorted array, see if it's smaller than the 'smallest' word that you took earlier + # If it is, put the smallest word back into the array, and replace 'smallest' with this new word + # If word is not smaller than the smallest, then push this word into the still unsorted array + + unsorted_array.each do | word | + if word < smallest + still_unsorted.push smallest + smallest = word + else + still_unsorted.push word + end + end + + # Put the smallest word into the sorted array + sorted_array.push smallest + + # Now call the same recursive sort method to sort out the still_unsorted words + recursive_sort still_unsorted, sorted_array + +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..1df218d2e 100644 --- a/ch11-reading-and-writing/build_a_better_playlist.rb +++ b/ch11-reading-and-writing/build_a_better_playlist.rb @@ -1,3 +1,38 @@ def music_shuffle filenames - # your code here + + filenames = filenames.sort + len = filenames.length + + 2.times do + l_idx = 0 # index of next card in left pile + r_idx = len/2 # index of next card in right pile + shuf = [] + + while shuf.length < len + if shuf.length%2 == 0 + shuf.push(filenames[r_idx]) + r_idx = r_idx + 1 + else + shuf.push(filenames[l_idx]) + l_idx = l_idx + 1 + end + end + + filenames = shuf + end + + arr = [] + cut = rand(len) # index of card to cut at + idx = 0 + + while idx < len + arr.push(filenames[(idx+cut)%len]) + idx = idx + 1 + end + + arr end + +songs = ['aa/bbb', 'aa/ccc', 'aa/ddd', 'AAA/xxxx', 'AAA/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..75e77a6f0 100644 --- a/ch11-reading-and-writing/build_your_own_playlist.rb +++ b/ch11-reading-and-writing/build_your_own_playlist.rb @@ -1 +1,39 @@ -# your code here \ No newline at end of file +def shuffle arr + recursive_shuffle arr, [] +end + +def recursive_shuffle original_array, shuffled_array + + if original_array.length <= 0 + return shuffled_array + end + + random_element = original_array.pop + shuffled_array.insert(rand(shuffled_array.length+1), random_element) + recursive_shuffle original_array, shuffled_array +end + +audio_files = Dir["../**/*.{MP3,mp3}"] + +if audio_files.length == 0 + puts "I'm sorry, I couldn't find any audio files in your collection." +else + puts "I found #{audio_files.length} audio files in your collection." + puts "What do you want to call your playlist?" + playlist_name = gets.chomp + playlist_name += ".m3u" + + shuffled_files = [] + shuffled_files = shuffle audio_files + + playlist = "" + + shuffled_files.each do |filename| + playlist += filename + "\n" + end + + File.open playlist_name, 'w' do |f| + f.write playlist + puts "I just wrote you a file called #{playlist_name}. Enjoy!" + end +end diff --git a/ch11-reading-and-writing/safer_picture_downloading.rb b/ch11-reading-and-writing/safer_picture_downloading.rb index 801de24bd..7ae7caa54 100644 --- a/ch11-reading-and-writing/safer_picture_downloading.rb +++ b/ch11-reading-and-writing/safer_picture_downloading.rb @@ -1 +1,36 @@ -# your code here \ No newline at end of file +pic_names = Dir["../*.{JPG,jpg}"] # Search in the parent directory + +puts "What would you like to call this batch?" +batch_name = gets.chomp + +puts +print "Downloading #{pic_names.length} files: " + +pic_number = 1 + +pic_names.each do |name| + print "." + new_name = if pic_number < 10 + "#{batch_name}0#{pic_number}.jpg" + else + "#{batch_name}#{pic_number}.jpg" + end + if File.exist? new_name + overwrite = gets.chomp "A file already exists with the name " + new_name + ". Do you want to overwrite? Type \"Yes\" or \"No\"." + if overwrite.downcase == "yes" + File.rename name, new_name + pic_number += 1 + elsif overwrite.downcase == "no" + puts "Skipping " + new_name + " because it already exists." + end + end +end + +puts +puts "Done, cutie!" + +# TO DO +# Add safety features to sure you never overwrite a file +# File.exist? (pass it a filename and it will return true or false) +# exit - kills your program right where it stands - good for spitting out an error message and then quitting +# ßSolve this in English first Frances! diff --git a/ch12-new-classes-of-objects/birthdates.txt b/ch12-new-classes-of-objects/birthdates.txt new file mode 100644 index 000000000..ea3492642 --- /dev/null +++ b/ch12-new-classes-of-objects/birthdates.txt @@ -0,0 +1,8 @@ +Christopher Alexander, Oct 4, 1936 +Christopher Lambert, Mar 29, 1957 +Christopher Lee, May 27, 1922 +Christopher Lloyd, Oct 22, 1938 +Christopher Pine, Aug 3, 1976 +Christopher Plummer, Dec 13, 1927 +Christopher Walken, Mar 31, 1943 +The King of Spain, Jan 5, 1938 diff --git a/ch12-new-classes-of-objects/birthday_helper.rb b/ch12-new-classes-of-objects/birthday_helper.rb index 801de24bd..072da5915 100644 --- a/ch12-new-classes-of-objects/birthday_helper.rb +++ b/ch12-new-classes-of-objects/birthday_helper.rb @@ -1 +1,26 @@ -# 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 "Whose birthday would you like to know?" +name = gets.chomp +date = birth_dates[name] + +if date == nil + puts "Oooh, 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..d1ec42a39 100644 --- a/ch12-new-classes-of-objects/happy_birthday.rb +++ b/ch12-new-classes-of-objects/happy_birthday.rb @@ -1 +1,20 @@ -# your code here \ No newline at end of file +puts "What year were you born in?" +year = gets.chomp + +puts "What month were you born in? (write as a number please)" +month = gets.chomp + +puts "What day were you born?" +day = gets.chomp + +birthday = Time.gm(year, month, day) + +puts "Your birthday is " + birthday.to_s + +years_alive = ((Time.new - birthday) / 31536000).to_i + +puts "Here, have a spank for the #{years_alive} years you've been alive!" + +years_alive.times do + puts "SPANK!" +end diff --git a/ch12-new-classes-of-objects/one_billion_seconds.rb b/ch12-new-classes-of-objects/one_billion_seconds.rb index 801de24bd..8f646ab12 100644 --- a/ch12-new-classes-of-objects/one_billion_seconds.rb +++ b/ch12-new-classes-of-objects/one_billion_seconds.rb @@ -1 +1,4 @@ -# your code here \ No newline at end of file +# Figure out what second I was born +# Calculate my one billionth second birthday + +puts Time.gm(1979, 5, 11, 02, 01) + 1000000000 diff --git a/ch12-new-classes-of-objects/party_like_its_roman_to_integer_mcmxcix.rb b/ch12-new-classes-of-objects/party_like_its_roman_to_integer_mcmxcix.rb index 037b6cb09..7727edcae 100644 --- a/ch12-new-classes-of-objects/party_like_its_roman_to_integer_mcmxcix.rb +++ b/ch12-new-classes-of-objects/party_like_its_roman_to_integer_mcmxcix.rb @@ -1,3 +1,31 @@ def roman_to_integer roman - # your code here -end \ No newline at end of file + # Reject strings which are not valid Roman numerals + + digit_vals = {"i" => 1, "v" => 5, "x" => 10, "l" => 50, "c" => 100, "d" => 500, "m" => 1000} + + total = 0 + prev = 0 + index = roman.length - 1 + + while index >= 0 + c = roman[index].downcase + index = index - 1 + val = digit_vals[c] + if !val + puts "This is not a valid roman numeral" + return + end + + if val < prev + val = val * -1 + else + prev = val + end + total = total + val + end + + total +end + +puts roman_to_integer "mcmxcix" +puts roman_to_integer "CCCLXV" diff --git a/ch13-creating-new-classes/extend_built_in_classes.rb b/ch13-creating-new-classes/extend_built_in_classes.rb index c3e793933..f54484a28 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 + numberMs = "M" * (self / 1000) + numberDs = "D" * ((self % 1000) / 500) + numberCs = "C" * ((self % 500) / 100) + numberLs = "L" * ((self % 100) / 50) + numberXs = "X" * ((self % 50) / 10) + numberVs = "V" * ((self % 10) / 5) + numberIs = "I" * ((self % 5) / 1) + + return numberMs + numberDs + numberCs + numberLs + numberXs + numberVs + numberIs + + end +end diff --git a/ch13-creating-new-classes/interactive_baby_dragon.rb b/ch13-creating-new-classes/interactive_baby_dragon.rb index 801de24bd..3210a2d91 100644 --- a/ch13-creating-new-classes/interactive_baby_dragon.rb +++ b/ch13-creating-new-classes/interactive_baby_dragon.rb @@ -1 +1,142 @@ -# your code here \ No newline at end of file +class Dragon + + def initialize name + @name = name + @asleep = false + @stuff_in_belly = 10 # He's full. + @stuff_in_intestine = 0 # He doesn't need to go. + puts "#{@name} is born." + self.ask_for_action + end + + def ask_for_action + puts + puts "What would you like to do with #{@name}? Please type 'feed', 'toss', 'walk', 'put to bed', or 'rock'." + action = gets.chomp + self.method_dispatch action.downcase + end + + def method_dispatch action + if action == "feed" + self.feed + elsif action == "toss" + self.toss + elsif action == "walk" + self.walk + elsif action == "put to bed" + self.put_to_bed + elsif action == "rock" + self.rock + else + puts "I'm sorry. I didn't understand your action." + self.ask_for_action + end + 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} up into the air." + puts 'He giggles, which singes your eyebrows.' + passage_of_time + end + + def rock + puts "You rock #{@name} gently." + @asleep = true + puts 'He briefly dozes off...' + passage_of_time + if @asleep + @asleep = false + puts '...but wakes when you stop.' + end + end + + private + + # "private" means that the methods defined here are + # methods internal to the object. (You can feed your + # dragon, but you can't ask him whether he's hungry.) + + def hungry? + + # Method names can end with "?". + # Usually, we do this only if the method + # returns true or false, like this: + @stuff_in_belly <= 2 + end + + def poopy? + @stuff_in_intestine >= 8 + end + + def passage_of_time + + if @stuff_in_belly > 0 + # Move food from belly to intestine. + @stuff_in_belly = @stuff_in_belly - 1 + @stuff_in_intestine = @stuff_in_intestine + 1 + else # Our dragon is starving! + if @asleep + @asleep = false + puts 'He wakes up suddenly!' + end + puts "#{@name} is starving! In desperation, he ate YOU!" + exit # This quits the program. + end + + if @stuff_in_intestine >= 10 + @stuff_in_intestine = 0 + puts "Whoops! #{@name} had an accident..." + end + + if hungry? + if @asleep + @asleep = false + puts 'He wakes up suddenly!' + end + puts "#{@name}'s stomach grumbles..." + end + + if poopy? + if @asleep + @asleep = false + puts 'He wakes up suddenly!' + end + puts "#{@name} does the potty dance..." + end + + self.ask_for_action + end + +end + +pet = Dragon.new 'Norbert' diff --git a/ch13-creating-new-classes/orange_tree.rb b/ch13-creating-new-classes/orange_tree.rb index 025d08907..a95f7a6f9 100644 --- a/ch13-creating-new-classes/orange_tree.rb +++ b/ch13-creating-new-classes/orange_tree.rb @@ -4,8 +4,134 @@ # 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 +class OrangeTree + + def initialize + @height = 0 + @orange_count = 0 + @alive = true + end + + def height + if @alive + @height.round(1) + 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 = @height + 0.4 + @orange_count = 0 # old oranges fall off + if @height > 10.1 + # tree dies + @alive = false + 'Oh, no! The tree is too old, and has died. :(' + elsif @height > 2 + # new oranges grow + @orange_count = (@height * 15 - 25).to_i + "This year your tree grew to #{@height.round(1)}m tall, and produced #{@orange_count} oranges." + else + "This year your tree grew to #{@height.round(1)}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 = @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 +=end +=begin +tree = OrangeTree.new +23.times do + tree.one_year_passes +end + +tree.one_year_passes +tree.count_the_oranges +tree.height + +5.times do + tree.one_year_passes +end + +tree.height +tree.count_the_oranges +tree.pick_an_orange +=end class OrangeTree - # your code here + + def initialize + @age = 0 + @height = 0 + @growth_rate = 0.4 + @age_first_fruit = 6 + @age_of_death = 26 + @orange_count = 0 + @alive = true + end + + def height + if @alive == false + "A dead tree is not very tall. :(" + else + @height + end + end + + def one_year_passes + @age += 1 + if @age < @age_of_death + @height = (@age * @growth_rate).round(2) + "This year your tree grew to #{self.height}m tall, and produced #{self.count_the_oranges} oranges." + elsif @age == @age_of_death + @alive = false + "Oh, no! The tree is too old, and has died. :(" + elsif @age > @age_of_death + "A year later, the tree is still dead. :(" + end + end + + def count_the_oranges + if @age < @age_first_fruit + @orange_count + elsif @alive == false + "A dead tree has no oranges. :(" + else + @orange_count = (@height * 15 - 25).to_i + end + end + + def pick_an_orange + if @alive == false + "A dead tree has nothing to pick. :(" + elsif @orange_count > 0 + @orange_count -= 1 + end + end + end diff --git a/ch14-blocks-and-procs/better_program_logger.rb b/ch14-blocks-and-procs/better_program_logger.rb index 0e2e18d57..896bf8eb2 100644 --- a/ch14-blocks-and-procs/better_program_logger.rb +++ b/ch14-blocks-and-procs/better_program_logger.rb @@ -1,3 +1,24 @@ -def log desc, &block - # your code here -end \ No newline at end of file +$logger_depth = 0 + +def better_log desc, &block + prefix = ' '*$logger_depth + puts prefix+"Beginning #{desc.inspect}..." + $logger_depth += 1 + result = block[] + $logger_depth -= 1 + puts prefix+"...#{desc.inspect} finished, returning: #{result}" +end + +better_log 'outer block' do + better_log 'some little block' do + better_log 'teeny-tiny block' do + 'lOtS oF lOVe'.downcase + end + 7 * 3 * 2 + end + + better_log 'yet another block' do + '!doof naidnI evol I'.reverse + end + '0' == "0" +end diff --git a/ch14-blocks-and-procs/even_better_profiling.rb b/ch14-blocks-and-procs/even_better_profiling.rb index b01b78fd8..ee7873792 100644 --- a/ch14-blocks-and-procs/even_better_profiling.rb +++ b/ch14-blocks-and-procs/even_better_profiling.rb @@ -1,3 +1,30 @@ def profile block_description, &block - # your code here -end \ No newline at end of file + + profiling_on = true + + if profiling_on + start_time = Time.new + block.call + duration = Time.new - start_time + puts "#{block_description}: #{duration} seconds" + else + block.call + end + +end + +profile '25000 doublings' do + number = 1 + 25000.times do + number = number + number + end + puts "#{number.to_s.length} digits" + # That's the number of digits in this HUGE number. +end + +profile 'count to a million' do + number = 0 + 1000000.times do + number = number + 1 + end +end diff --git a/ch14-blocks-and-procs/grandfather_clock.rb b/ch14-blocks-and-procs/grandfather_clock.rb index 916f6d354..a8323b464 100644 --- a/ch14-blocks-and-procs/grandfather_clock.rb +++ b/ch14-blocks-and-procs/grandfather_clock.rb @@ -1,3 +1,19 @@ def grandfather_clock &block - # your code here -end \ No newline at end of file + 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..3438199fb 100644 --- a/ch14-blocks-and-procs/program_logger.rb +++ b/ch14-blocks-and-procs/program_logger.rb @@ -1,3 +1,17 @@ -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