diff --git a/ch09-writing-your-own-methods/ask.rb b/ch09-writing-your-own-methods/ask.rb index 01716eb35..942b8ad91 100644 --- a/ch09-writing-your-own-methods/ask.rb +++ b/ch09-writing-your-own-methods/ask.rb @@ -1,3 +1,29 @@ 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 + else + puts 'Please answer "yes" or "no".' + end + end +end + + puts 'Hello, and thank you for...' + puts + ask 'Do you like eating tacos?' + wets_bed = ask 'Do you wet the bed?' + 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 'Thank you for...' + puts + 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..dbbd4574a 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,12 @@ def old_roman_numeral num - # your code here -end \ No newline at end of file + roman_numeral = "" + roman_numeral = roman_numeral + "M" * (num / 1000) + roman_numeral = roman_numeral + "D" * (num % 1000 / 500) + roman_numeral = roman_numeral + "C" * (num % 500 / 100) + roman_numeral = roman_numeral + "L" * (num % 100 /50) + roman_numeral = roman_numeral + "X" * (num % 50 / 10) + roman_numeral = roman_numeral + "V" * (num % 10 / 5) + roman_numeral = roman_numeral + "I" * (num % 5 / 1) +end + +puts old_roman_numeral(2456) diff --git a/ch09-writing-your-own-methods/roman_numerals.rb b/ch09-writing-your-own-methods/roman_numerals.rb index 5c93b59ac..72647d2e5 100644 --- a/ch09-writing-your-own-methods/roman_numerals.rb +++ b/ch09-writing-your-own-methods/roman_numerals.rb @@ -1,3 +1,42 @@ def roman_numeral num - # your code here -end \ No newline at end of file + roman_numeral = "" + + thousands = (num / 1000) + hundreds = (num % 1000 / 100) + tens = (num % 100 / 10) + singles = (num % 10 / 1) + + roman_numeral = "M" * thousands + + if hundreds == 9 + roman_numeral = roman_numeral + "CM" + elsif hundreds == 4 + roman_numeral = roman_numeral + "CD" + else + roman_numeral = roman_numeral + "D" * (num % 1000 / 500) + roman_numeral = roman_numeral + "C" * (num % 500 / 100) + end + + if tens == 9 + roman_numeral = roman_numeral + "XC" + elsif tens == 4 + roman_numeral = roman_numeral + "XL" + else + roman_numeral = roman_numeral + "L" * (num % 100 / 50) + roman_numeral = roman_numeral + "X" * (num % 50 / 10) + end + + if singles == 9 + roman_numeral = roman_numeral + "IX" + elsif singles == 4 + roman_numeral = roman_numeral + "IV" + else + roman_numeral = roman_numeral + "V" * (num % 10 / 5) + roman_numeral = roman_numeral + "I" * (num % 5 / 1) + end + + roman_numeral + +end + +puts roman_numeral(2644) diff --git a/ch10-nothing-new/dictionary_sort.rb b/ch10-nothing-new/dictionary_sort.rb index c9893d0fd..f286e2e4f 100644 --- a/ch10-nothing-new/dictionary_sort.rb +++ b/ch10-nothing-new/dictionary_sort.rb @@ -1,3 +1,23 @@ -def dictionary_sort arr - # your code here -end \ No newline at end of file +def dictionary_sort array + recursive_dictionary_sort array, [] +end + +def recursive_dictionary_sort unsorted, sorted + if unsorted.length <= 0 + return sorted + end + smallest = unsorted.pop + still_unsorted = [] + unsorted.each do |test_object| + if test_object.downcase < smallest.downcase + still_unsorted.push smallest + smallest = test_object + else + still_unsorted.push test_object + end + end + sorted.push smallest + recursive_dictionary_sort still_unsorted, sorted +end + +puts(dictionary_sort(['can','feel','singing','Like','A','can'])) diff --git a/ch10-nothing-new/english_number.rb b/ch10-nothing-new/english_number.rb index c0129bc4e..e01167245 100644 --- a/ch10-nothing-new/english_number.rb +++ b/ch10-nothing-new/english_number.rb @@ -1,3 +1,130 @@ def english_number number - # your code here + if number < 0 # No negative numbers. + return 'Please enter a number that isn\'t negative.' + end + if number == 0 + return 'zero' + end + + # No more special cases! No more returns! + + num_string = '' # This is the string we will return. + + 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], + ['sexdecillion', 51], + ['septendecillion', 54], + ['octodecillion', 57], + ['novemdecillion', 60], + ['vigintillion', 63], + ['googol', 100]] + + # "left" is how much of the number + # we still have left to write out. + # "write" is the part we are + # writing out right now. + # write and left...get it? :) + 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 # How many zillions left? + left = left - write*zil_base # Subtract off those zillions. + + if write > 0 + # Now here's the recursion: + prefix = english_number write + num_string = num_string + prefix + ' ' + zil_name + + if left > 0 + # So we don't write 'two billionfifty-one'... + num_string = num_string + ' ' + end + end + end + + write = left/10 # How many tens left? + left = left - write*10 # Subtract off those tens. + + if write > 0 + if ((write == 1) and (left > 0)) + # Since we can't write "tenty-two" instead of + # "twelve", we have to make a special exception + # for these. + num_string = num_string + teenagers[left-1] + # The "-1" is because teenagers[3] is + # 'fourteen', not 'thirteen'. + + # Since we took care of the digit in the + # ones place already, we have nothing left to write. + left = 0 + else + num_string = num_string + tens_place[write-1] + # The "-1" is because tens_place[3] is + # 'forty', not 'thirty'. + end + + if left > 0 + # So we don't write 'sixtyfour'... + num_string = num_string + '-' + end + end + + write = left # How many ones left to write out? + left = 0 # Subtract off those ones. + + if write > 0 + num_string = num_string + ones_place[write-1] + # The "-1" is because ones_place[3] is + # 'four', not 'three'. + end + + # Now we just return "num_string"... + num_string end + +# puts english_number( 0) +# puts english_number( 9) +# puts english_number( 10) +# puts english_number( 11) +# puts english_number( 17) +# puts english_number( 32) +# puts english_number( 88) +# puts english_number( 99) +# puts english_number(100) +# puts english_number(101) +# puts english_number(234) +# puts english_number(3211) +# puts english_number(999999) +# puts english_number(1000000000000) +# puts english_number(109238745102938560129834709285360238475982374561034) diff --git a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb index 801de24bd..619d7bfb5 100644 --- a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb +++ b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb @@ -1 +1,79 @@ -# your code here \ No newline at end of file +def englishNumber number + + if number < 0 + return "Please enter a number which isn't negative" + end + if number == 0 + return "zero" + end + + numString = "" + + onesPlace = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] + tensPlace = ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] + teenPlace = ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] + hugeNumber = [["hundred", 2],["thousand", 3], ["million", 6], ["billion", 9], ["trillion", 12], ["quadrillion", 15]] + + left = number + + while hugeNumber.length > 0 + hugeNumber_pair = hugeNumber.pop + hugeNumber_name = hugeNumber_pair[0] + hugeNumber_base = 10 ** hugeNumber_pair[1] + write = left / hugeNumber_base + left = left - write * hugeNumber_base + + if write > 0 + prefix = englishNumber write + numString = numString + prefix + "-" + hugeNumber_name + end + + if left > 0 + numString = numString + "" + end + end + + + write = left/10 + left = left - write*10 + + if write > 0 + if ((write == 1) and (left > 0)) + numString = numString + teenPlace[left-1] + left = 0 + else + numString = numString + tensPlace[write-1] + end + + if left > 0 + numString = numString + "-" + end + end + + write = left + left = 0 + + if write > 0 + numString = numString + onesPlace[write-1] + end + + numString + +end + + +bottle_starting_count = 10 +bottle_count = bottle_starting_count +while bottle_count > 1 + puts englishNumber(bottle_count).capitalize + " bottles of beer on the wall" + puts englishNumber(bottle_count).capitalize + " bottles of beer" + puts "You take 1 down, pass it around" + bottle_count = bottle_count - 1 + puts englishNumber(bottle_count).capitalize + " bottles of beer on the wall" + +end + +puts "One bottle of beer on the wall" +puts "One bottle of beer" +puts "You take 1 down, pass it around" +puts "No more bottles of beer on the wall" diff --git a/ch10-nothing-new/shuffle.rb b/ch10-nothing-new/shuffle.rb index a486ad94c..b80bbd52a 100644 --- a/ch10-nothing-new/shuffle.rb +++ b/ch10-nothing-new/shuffle.rb @@ -1,3 +1,25 @@ -def shuffle arr - # your code here -end \ No newline at end of file +def shuffle array + shuffled = [] + + while array.length > 0 + + random_index = rand(array.length) + + current_index = 0 + new_array = [] + + array.each do |index| + if current_index == random_index + shuffled.push index + else + new_array.push index + end + current_index = current_index + 1 + end + + array = new_array + end + shuffled +end + +puts(shuffle(["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"])) diff --git a/ch10-nothing-new/sort.rb b/ch10-nothing-new/sort.rb index 44c6deb58..431886156 100644 --- a/ch10-nothing-new/sort.rb +++ b/ch10-nothing-new/sort.rb @@ -1,3 +1,23 @@ -def sort arr - # your code here -end \ No newline at end of file +def sort array + recursive_sort array, [] +end + +def recursive_sort unsorted, sorted + if unsorted.length <= 0 + return sorted + end + smallest = unsorted.pop + still_unsorted = [] + unsorted.each do |test_object| + if test_object < smallest + still_unsorted.push smallest + smallest = test_object + else + still_unsorted.push test_object + end + end + sorted.push smallest + recursive_sort still_unsorted, sorted +end + +puts(sort(['can','feel','singing','like','a','can'])) diff --git a/ch11-reading-and-writing/build_a_better_playlist.rb b/ch11-reading-and-writing/build_a_better_playlist.rb index 3b31bd241..099626a7d 100644 --- a/ch11-reading-and-writing/build_a_better_playlist.rb +++ b/ch11-reading-and-writing/build_a_better_playlist.rb @@ -1,3 +1,37 @@ def music_shuffle filenames - # your code here + len = filenames.length + #obtian the files length + 2.times do + l_idx = 0 + r_idx = len / 2 + shuf = [] +#create a vegas style deck shuffle + 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) + idx = 0 +#randomly cut the deck via the filename length + while idx < len + arr.push(filenames[(idx+cut)%len]) + idx = idx + 1 + end +#push filenames in the open array +arr end +#output the array + +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..d4e0dba33 100644 --- a/ch11-reading-and-writing/build_your_own_playlist.rb +++ b/ch11-reading-and-writing/build_your_own_playlist.rb @@ -1 +1,37 @@ -# your code here \ No newline at end of file +def shuffle array + shuffled = [] +#open an empy array + while array.length > 0 + random_index = rand(array.length) +#randomise the array using length as the point of randomisation + current_index = 0 + new_array = [] +#creates an open array and sets the initial index position + array.each do |index| + if current_index == random_index + shuffled.push index + #ensures the index is moving + else + new_array.push index + #pushes values to the new array + end + current_index = current_index + 1 + #increases the current index position + end + + array = new_array + end + shuffled + #runs the shufled method +end + +music_files = shuffle(Dir["**/*.mp3"]) +#gains files from the specified directory and shuffles the files using the above method +File.open "new_playlist.m3u", 'w' do |add| + music_files.each do |mp3| + add.write mp3 + "\n" + #add the mp3 file to the playlist and a new line + end +end + +puts "Complete." diff --git a/ch11-reading-and-writing/safer_picture_downloading.rb b/ch11-reading-and-writing/safer_picture_downloading.rb index 801de24bd..114302523 100644 --- a/ch11-reading-and-writing/safer_picture_downloading.rb +++ b/ch11-reading-and-writing/safer_picture_downloading.rb @@ -1 +1,25 @@ -# your code here \ No newline at end of file +Dir.chdir '~/pictures' + +pic_names = Dir['~/ExternalHD/Picturs'] +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 + + File.rename name, new_name + pic_number = pic_number + 1 +end +puts +puts 'Done!' diff --git a/ch12-new-classes-of-objects/birthday_helper.rb b/ch12-new-classes-of-objects/birthday_helper.rb index 801de24bd..14fc38894 100644 --- a/ch12-new-classes-of-objects/birthday_helper.rb +++ b/ch12-new-classes-of-objects/birthday_helper.rb @@ -1 +1,28 @@ -# your code here \ No newline at end of file +birth_dates = {} +File.read('birthdates.txt').each_line do |line| + line = line.chomp +# Load the file and separate the list onto separate lines. + first_comma = 0 + while line[first_comma] != ',' && + first_comma < line.length + first_comma = first_comma + 1 + end + # Separate the data using the commas as split points + name = line[0..(first_comma - 1)] + date = line[-12..-1] + birth_dates[name] = date + # Store the names and dates from the File +end + +puts 'Whose birthday would you like to know?' +name = gets.chomp +# Get user input about who's birthday they would like to know +date = birth_dates[name] + +if date == nil + puts "Oooh, I don't know that one..." + # If the name doesn't exist in the file output +else + puts date[0..5] + # Output the date from the File +end diff --git a/ch12-new-classes-of-objects/happy_birthday.rb b/ch12-new-classes-of-objects/happy_birthday.rb index 801de24bd..ee9425fe1 100644 --- a/ch12-new-classes-of-objects/happy_birthday.rb +++ b/ch12-new-classes-of-objects/happy_birthday.rb @@ -1 +1,35 @@ -# your code here \ No newline at end of file +puts "What year were you born in?" +year = gets.chomp.to_i + +puts "What month were you born in? (1 - 12)" +month = gets.chomp.to_i + +puts "What day were you born on?" +day = gets.chomp.to_i + +current_time = Time.new +birth_time = Time.gm(year, month, day) + +current_time_year = current_time.year +current_time_month = current_time.month +current_time_day = current_time.day + +if current_time_month > month + spank_times = current_time_year - year + spank_times.times {puts "SPANK!"} +elsif current_time_month == month + if current_time_day > day + spank_times = current_time_year - year + spank_times.times {puts "SPANK!"} + elsif current_time_day == day + puts "Happy Birthday!" + spank_times = current_time_year - year + spank_times.times {puts "SPANK!"} + else + spank_times = current_time_year - year -1 + spank_times.times {puts "SPANK!"} + end +else + spank_times = current_time_year - year -1 + spank_times.times {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..821e9e0fd 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 +puts(Time.gm(1986, 11, 21, 00, 15) + 10**9) +#get the time and add 1 billion seconds (10**9) 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..1470dada4 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,41 @@ def roman_to_integer roman - # your code here -end \ No newline at end of file + digit_vals = { + 'i' => 1, + 'v' => 5, + 'x' => 10, + 'l' => 50, + 'c' => 100, + 'd' => 500, + 'm' => 1000} + #setting the roman numeral letters to values utilising a hash + total = 0 + prev = 0 + #setting up the initial conditions + index = roman.length - 1 + #starting with the initial index position + while index >= 0 + c = roman[index].downcase + #ensuring all the roman numerals are in lowercase so don't have to work with both cases + index = index - 1 + val = digit_vals[c] + #moving the index along the numeral and comparing to the hash to ensure they are all roman numerals + if !val + puts 'This is not a valid roman numeral!' + return + #ensuring a valid roman numeral was entered + end + if val < prev + val = val * -1 + #ensuring it is a positive value + else + prev = val + end + total = total + val + #calculating the value + end +total +#output total value +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..b6f15d685 100644 --- a/ch13-creating-new-classes/extend_built_in_classes.rb +++ b/ch13-creating-new-classes/extend_built_in_classes.rb @@ -1,3 +1,23 @@ class Integer - # your code here -end \ No newline at end of file + + def factorial + raise 'Must not use negative integer' if self < 0 + (self <= 1) ? 1 : self * (self-1).factorial + end + + def to_roman + roman_numeral = "" + + roman_numeral = roman_numeral + "M" * (self / 1000) + roman_numeral = roman_numeral + "D" * (self % 1000 / 500) + roman_numeral = roman_numeral + "C" * (self % 500 / 100) + roman_numeral = roman_numeral + "L" * (self % 100 /50) + roman_numeral = roman_numeral + "X" * (self % 50 / 10) + roman_numeral = roman_numeral + "V" * (self % 10 / 5) + roman_numeral = roman_numeral + "I" * (self % 5 / 1) + + roman_numeral + end +end + +puts 26.to_roman diff --git a/ch13-creating-new-classes/interactive_baby_dragon.rb b/ch13-creating-new-classes/interactive_baby_dragon.rb index 801de24bd..10938934d 100644 --- a/ch13-creating-new-classes/interactive_baby_dragon.rb +++ b/ch13-creating-new-classes/interactive_baby_dragon.rb @@ -1 +1,125 @@ -# your code here \ No newline at end of file +class Dragon + def initialize name + @name = name + @asleep = 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} 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 + 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 = @stuff_in_belly - 1 + @stuff_in_intestine = @stuff_in_intestine + 1 + else + if @asleep + @asleep = false + puts 'He wakes up suddenly!' + end + puts "#{@name} is starving! In desperation, he ate YOU!" + exit + 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 +end +end + +puts 'What would you like to name your baby dragon?' +name = gets.chomp +pet = Dragon.new name + +while true + puts + puts 'commands: feed, toss, walk, rock, put to bed, exit' + command = 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..c7e1796e7 100644 --- a/ch13-creating-new-classes/orange_tree.rb +++ b/ch13-creating-new-classes/orange_tree.rb @@ -7,5 +7,59 @@ class OrangeTree - # your code here + def initialize + @height = 0 + @orange_count = 0 + @alive = true + end +# Initializing the starting values and local variables + def height + if @alive + @height.round(1) + else + 'A dead tree is not very tall. :(' + end + end +# Checking if still alive and calling upon then height variable + def count_the_oranges + if @alive + @orange_count + else + 'A dead tree has no oranges. :(' + end + end +# Checking if alive and calling on the orange count + def one_year_passes + if @alive + @height = @height + 0.4 # Incrementing the height of the tree + @orange_count = 0 # old oranges fall off + if @height > 10 && rand(2) > 0 + # tree dies + @alive = false + 'Oh, no! The tree is too old, and has died. :(' + elsif @height > 2 + @orange_count = (@height * 15 - 25).to_i # Calculating how many new oranges grow + "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 # Decreasing the local variable for orange count + '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 diff --git a/ch14-blocks-and-procs/better_program_logger.rb b/ch14-blocks-and-procs/better_program_logger.rb index 0e2e18d57..10ef01a3b 100644 --- a/ch14-blocks-and-procs/better_program_logger.rb +++ b/ch14-blocks-and-procs/better_program_logger.rb @@ -1,3 +1,30 @@ -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 + '"...' + + $logger_depth = $logger_depth + 1 + + result = block.call + + $logger_depth = $logger_depth - 1 + puts prefix + '..."' + desc + '" finished, returning: ' + result.to_s +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..c6812af9e 100644 --- a/ch14-blocks-and-procs/even_better_profiling.rb +++ b/ch14-blocks-and-procs/even_better_profiling.rb @@ -1,3 +1,13 @@ def profile block_description, &block - # your code here -end \ No newline at end of file + profiling_on = false + + if profiling_on = true + 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..9f73bde3f 100644 --- a/ch14-blocks-and-procs/grandfather_clock.rb +++ b/ch14-blocks-and-procs/grandfather_clock.rb @@ -1,3 +1,18 @@ def grandfather_clock &block - # your code here -end \ No newline at end of file + hour = Time.new.hour + + if hour >= 13 + hour = 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