From a5cb7aaedbd091e26610c3e95beeeecfc12e156a Mon Sep 17 00:00:00 2001 From: stuartcooper Date: Mon, 5 Sep 2016 15:46:10 +0100 Subject: [PATCH 1/7] Adding Ch09 --- ch09-writing-your-own-methods/ask.rb | 30 +++++++++++++- .../old_school_roman_numerals.rb | 16 +++++++- .../roman_numerals.rb | 39 ++++++++++++++++++- 3 files changed, 79 insertions(+), 6 deletions(-) diff --git a/ch09-writing-your-own-methods/ask.rb b/ch09-writing-your-own-methods/ask.rb index 01716eb35..2e3879d71 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 + + return true if reply == 'yes' + return false if reply == 'no' + + puts 'Please answer "yes" or "no".' + end + + answer # This is the return of true or false +end +puts 'Hello, and thank you for...' +puts +ask 'Do you like eating tacos?' +ask 'Do you like eating burrittos?' +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 'DEBREIFING:' +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..a0d16a230 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,15 @@ def old_roman_numeral num - # your code here -end \ No newline at end of file + numeral = '' + + numeral = numeral + 'M' * (num / 1000) + numeral = numeral + 'D' * (num % 1000 / 500) + numeral = numeral + 'C' * (num % 500 / 100) + numeral = numeral + 'L' * (num % 100 / 50) + numeral = numeral + 'X' * (num % 50 / 10) + numeral = numeral + 'V' * (num % 10 / 5) + numeral = numeral + 'I' * (num % 5 / 1) + + numeral +end + +puts old_roman_numeral(2016) diff --git a/ch09-writing-your-own-methods/roman_numerals.rb b/ch09-writing-your-own-methods/roman_numerals.rb index 5c93b59ac..9d8be19c7 100644 --- a/ch09-writing-your-own-methods/roman_numerals.rb +++ b/ch09-writing-your-own-methods/roman_numerals.rb @@ -1,3 +1,38 @@ def roman_numeral num - # your code here -end \ No newline at end of file + thousand = (num / 1000) + hundred = (num % 1000 / 100) + ten = (num % 100 / 10) + one = (num % 10) + + numeral = 'M' * thousand + + if hundred == 9 + numeral = numeral + 'CM' + elsif hundred == 4 + numeral = numeral + 'CD' + else + numeral = numeral + 'D' * (num % 1000 / 500) + numeral = numeral + 'C' * (num % 500 / 100) + end + + if ten == 9 + numeral = numeral + 'XC' + elsif ten == 4 + numeral = numeral + 'XL' + else + numeral = numeral + 'L' * (num % 100 / 50) + numeral = numeral + 'X' * (num % 50 / 10) + end + + if one == 9 + numeral = numeral + 'IX' + elsif numeral == 4 + numeral = numeral = 'IV' + else + numeral = numeral + 'V' * (num % 10 / 5) + numeral = numeral + 'I' * (num % 5 / 1) + end + numeral +end + +puts roman_numeral(2016) From f08089e310758a4a258964f5627d231e9ea802cf Mon Sep 17 00:00:00 2001 From: stuartcooper Date: Tue, 6 Sep 2016 14:51:10 +0100 Subject: [PATCH 2/7] Adding shuffle challenge --- ch10-nothing-new/shuffle.rb | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/ch10-nothing-new/shuffle.rb b/ch10-nothing-new/shuffle.rb index a486ad94c..e32c02922 100644 --- a/ch10-nothing-new/shuffle.rb +++ b/ch10-nothing-new/shuffle.rb @@ -1,3 +1,26 @@ def shuffle arr - # your code here -end \ No newline at end of file + shuf = [] +#shuffle an array of any size above zero + while arr.length > 0 + rand_index = rand(arr.length) +#iterate each item placing all bar the random one in the new array which goes into shuf + 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 = curr_index + 1 + end + #call back new array instead of original array + arr = new_arr + end + + shuf +end + +puts(shuffle([1, 9, 2, 8, 3, 7, 4, 6, 5])) From c802a301959338eccfe039370cf45ad2201d4ac9 Mon Sep 17 00:00:00 2001 From: stuartcooper Date: Tue, 6 Sep 2016 17:00:10 +0100 Subject: [PATCH 3/7] Adding Ch10 --- ch10-nothing-new/dictionary_sort.rb | 13 ++- ch10-nothing-new/english_number.rb | 104 +++++++++++++++++- .../ninety_nine_bottles_of_beer.rb | 79 ++++++++++++- ch10-nothing-new/shuffle.rb | 2 +- ch10-nothing-new/sort.rb | 30 ++++- 5 files changed, 221 insertions(+), 7 deletions(-) diff --git a/ch10-nothing-new/dictionary_sort.rb b/ch10-nothing-new/dictionary_sort.rb index c9893d0fd..0988ba934 100644 --- a/ch10-nothing-new/dictionary_sort.rb +++ b/ch10-nothing-new/dictionary_sort.rb @@ -1,3 +1,12 @@ def dictionary_sort arr - # your code here -end \ No newline at end of file + return arr if arr.length <= 1 + + middle = arr.pop + less = arr.select{|x| x.downcase < middle.downcase} + more = arr.select{|x| x.downcase >= middle.downcase} + +dictionary_sort(less) + [middle] + dictionary_sort(more) +end + +words = ['hakuna', 'Matata', 'what', 'a', 'wonderful', 'phrase'] +puts(dictionary_sort(words).join(' ')) diff --git a/ch10-nothing-new/english_number.rb b/ch10-nothing-new/english_number.rb index c0129bc4e..2a6b0f50c 100644 --- a/ch10-nothing-new/english_number.rb +++ b/ch10-nothing-new/english_number.rb @@ -1,3 +1,105 @@ 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]] +# "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!! + +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/100 # How many hundreds left? +left = left - write*100 # Subtract off those hundreds. + if write > 0 +# Now here's the recursion: + hundreds = english_number write + num_string = num_string + hundreds + ' hundred' + + if left > 0 +# So we don't write 'two hundredfifty-one'... + num_string = num_string + ' ' + 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) diff --git a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb index 801de24bd..8278266c7 100644 --- a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb +++ b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb @@ -1 +1,78 @@ -# your code here \ No newline at end of file +# def english_number number + 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'] + +# "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 +write = left/100 # How many hundreds left? +left = left - write*100 # Subtract off those hundreds. + if write > 0 +# Now here's the recursion: + hundreds = english_number write + num_string = num_string + hundreds + ' hundred' + + if left > 0 +# So we don't write 'two hundredfifty-one'... + num_string = num_string + ' ' + 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 + +num_at_start = 10 # change to 9999 if you want +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 = num_now - 1 + puts 'Take one down, pass it around, ' + + english_number(num_now) + ' bottles of beer on the wall!' +end diff --git a/ch10-nothing-new/shuffle.rb b/ch10-nothing-new/shuffle.rb index e32c02922..a941b573e 100644 --- a/ch10-nothing-new/shuffle.rb +++ b/ch10-nothing-new/shuffle.rb @@ -23,4 +23,4 @@ def shuffle arr shuf end -puts(shuffle([1, 9, 2, 8, 3, 7, 4, 6, 5])) +puts(shuffle([1,9,2,8,3,7,4,6,5])) diff --git a/ch10-nothing-new/sort.rb b/ch10-nothing-new/sort.rb index 44c6deb58..13e4eb8eb 100644 --- a/ch10-nothing-new/sort.rb +++ b/ch10-nothing-new/sort.rb @@ -1,3 +1,29 @@ def sort arr - # your code here -end \ No newline at end of file + rec_sort arr, [] + end + + def rec_sort unsorted, sorted + if unsorted.length <= 0 + return sorted + end + # So if we got here, then it means we still # have work to do. + smallest = unsorted.pop + still_unsorted = [] + + unsorted.each do |tested_object| + if tested_object < smallest + still_unsorted.push smallest + smallest = tested_object + else + still_unsorted.push tested_object + end + end + + # Now "smallest" really does point to the + # smallest element that "unsorted" contained, + # and all the rest of it is in "still_unsorted". l + sorted.push smallest + + rec_sort still_unsorted, sorted + end +puts(sort([' can' ,' feel' ,' singing' ,' like' ,' a' ,' can' ])) From d8b1e12699e7365b1962be9367f02e2d31f21d87 Mon Sep 17 00:00:00 2001 From: stuartcooper Date: Wed, 7 Sep 2016 15:55:23 +0100 Subject: [PATCH 4/7] Adding Ch11 --- .../build_a_better_playlist.rb | 50 +++++++++- .../build_your_own_playlist.rb | 50 +++++++++- .../safer_picture_downloading.rb | 99 ++++++++++++++++++- 3 files changed, 196 insertions(+), 3 deletions(-) diff --git a/ch11-reading-and-writing/build_a_better_playlist.rb b/ch11-reading-and-writing/build_a_better_playlist.rb index 3b31bd241..b3538aef9 100644 --- a/ch11-reading-and-writing/build_a_better_playlist.rb +++ b/ch11-reading-and-writing/build_a_better_playlist.rb @@ -1,3 +1,51 @@ def music_shuffle filenames - # your code here + # We don't want a perfectly random shuffle, so let's + # instead do a shuffle like card-shuffling. Let's + # shuffle the "deck" twice, then cut it once. That's + # not enough times to make a perfect shuffle, but it + # does mix things up a bit. + # Before we do anything, let's actually *sort* the + # input, since we don't know how shuffled it might + # already be, and we don't want it to be *too* random. + filenames = filenames.sort + len = filenames.length + + # Now we shuffle twice. + 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 = [] + # NOTE: If we have an odd number of "cards", + # then the right pile will be larger. + + while shuf.length < len + if shuf.length%2 == 0 + # take card from right pile + shuf.push(filenames[r_idx]) + r_idx = r_idx + 1 + else + # take card from left pile + shuf.push(filenames[l_idx]) + l_idx = l_idx + 1 + end + end + + filenames = shuf + end + # And cut the deck. + 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)) + end diff --git a/ch11-reading-and-writing/build_your_own_playlist.rb b/ch11-reading-and-writing/build_your_own_playlist.rb index 801de24bd..14ec08946 100644 --- a/ch11-reading-and-writing/build_your_own_playlist.rb +++ b/ch11-reading-and-writing/build_your_own_playlist.rb @@ -1 +1,49 @@ -# your code here \ No newline at end of file +def music_shuffle filenames + + filenames = filenames.sort + len = filenames.length + + # Now we shuffle twice. + 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 = [] + # NOTE: If we have an odd number of "cards", + # then the right pile will be larger. + + while shuf.length < len + if shuf.length%2 == 0 + # take card from right pile + shuf.push(filenames[r_idx]) + r_idx = r_idx + 1 + else + # take card from left pile + shuf.push(filenames[l_idx]) + l_idx = l_idx + 1 + end + end + + filenames = shuf + end + # And cut the deck. + 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 + +all_oggs = shuffle(Dir['**/*.ogg']) + +File.open 'playlist.m3u', 'w' do |f| + all_oggs.each do |ogg| + f.write ogg+"\n" + end +end + +puts 'Done!' diff --git a/ch11-reading-and-writing/safer_picture_downloading.rb b/ch11-reading-and-writing/safer_picture_downloading.rb index 801de24bd..ddebd5379 100644 --- a/ch11-reading-and-writing/safer_picture_downloading.rb +++ b/ch11-reading-and-writing/safer_picture_downloading.rb @@ -1 +1,98 @@ -# your code here \ No newline at end of file +# For Katy, with love. + +### Download pictures from camera card. + +require 'win32ole' + +STDOUT.sync = true +Thread.abort_on_exception = true + +Dir.chdir 'C:\Documents and Settings\Chris\Desktop\pictureinbox' + +# Always look here for pics. + +pic_names = Dir['!undated/**/*.{jpg,avi}'] +thm_names = Dir['!undated/**/*.{thm}' ] + +# Scan for memory cards in the card reader. +WIN32OLE.new("Scripting.FileSystemObject").Drives.each() do |x| + #driveType 1 is removable disk + if x.DriveType == 1 && x.IsReady + pic_names += Dir[x.DriveLetter+':/**/*.{jpg,avi}'] + thm_names += Dir[x.DriveLetter+':/**/*.{thm}' ] + end +end + +months = %w(jan feb mar apr may jun jul aug sep oct nov dec) + +encountered_error = false + +print "Downloading #{pic_names.size} files: " + +pic_names.each do |name| + print '.' + is_movie = (name[-3..-1].downcase == 'avi') + + if is_movie + orientation = 0 + new_name = File.open(name) do |f| + f.seek(0x144,IO::SEEK_SET) + f.read(20) + end + + new_name[0...3] = '%.2d' % (1 + months.index(new_name[0...3].downcase)) + new_name = new_name[-4..-1] + ' ' + new_name[0...-5] + else + new_name, orientation = File.open(name) do |f| + f.seek(0x36, IO::SEEK_SET) + orientation_ = f.read(1)[0] + f.seek(0xbc, IO::SEEK_SET) + new_name_ = f.read(19) + [new_name_, orientation_] + end + end + + [4,7,10,13,16].each {|n| new_name[n] = '.'} + if new_name[0] != '2'[0] + encountered_error = true + puts "\n"+'ERROR: Could not process "'+name+ + '" because it\'s not in the proper format!' + next + end + + save_name = new_name + (is_movie ? '.orig.avi' : '.jpg') + # Make sure we don't save over another file!! + while FileTest.exist? save_name + new_name += 'a' + save_name = new_name + (is_movie ? '.orig.avi' : '.jpg') + end + + + case orientation + when 6 + `convert "#{name}" -rotate "90>" "#{save_name}"` + File.delete name + when 8 + `convert "#{name}" -rotate "-90>" "#{save_name}"` + File.delete name + else + File.rename name, save_name + end +end + +print "\nDeleting #{thm_names.size} THM files: " +thm_names.each do |name| + print '.' + File.delete name +end + +# If something bad happened, make sure she + +# sees the error message before the window closes. + +if encountered_error + puts + puts "Press [Enter] to finish." + puts + gets +end From b303cac412cc4d321dca24ae97abf3903ee83898 Mon Sep 17 00:00:00 2001 From: stuartcooper Date: Wed, 7 Sep 2016 17:31:18 +0100 Subject: [PATCH 5/7] Adding Ch12 --- .../birthday_helper.rb | 28 +++++++++++++++- ch12-new-classes-of-objects/happy_birthday.rb | 24 +++++++++++++- .../one_billion_seconds.rb | 2 +- ...party_like_its_roman_to_integer_mcmxcix.rb | 33 +++++++++++++++++-- 4 files changed, 82 insertions(+), 5 deletions(-) diff --git a/ch12-new-classes-of-objects/birthday_helper.rb b/ch12-new-classes-of-objects/birthday_helper.rb index 801de24bd..90b852e66 100644 --- a/ch12-new-classes-of-objects/birthday_helper.rb +++ b/ch12-new-classes-of-objects/birthday_helper.rb @@ -1 +1,27 @@ -# your code here \ No newline at end of file +# First, load in the birthdates. +birth_dates = {} +File.read('birthdates.txt').each_line do |line| + line = line.chomp + # Find the index of first comma, + # so we know where the name ends. + first_comma = 0 + while line[first_comma] != ',' && + first_comma < line.length + first_comma = first_comma + 1 + end + + name = line[0..(first_comma - 1)] + date = line[-12..-1] + birth_dates[name] = date +end + +# Now ask the user which one they want to know. +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..a1bfe557e 100644 --- a/ch12-new-classes-of-objects/happy_birthday.rb +++ b/ch12-new-classes-of-objects/happy_birthday.rb @@ -1 +1,23 @@ -# your code here \ No newline at end of file +#Ask what year the person was born in +puts "What year were you born in?" +year = gets.chomp.to_i +#Ask what month +puts "What month were you born in?" +month = gets.chomp.to_i +#Ask what date +puts "What date of month were you born on?" +date = gets.chomp.to_i + +born = Time.local(year, month, date) +today = Time.new + +puts "So you were born on the #{born}?" + +age = 1 + +puts "Have a SPANK for each year you've been alive!" + +while Time.local(year + age, month, date) <= today +puts 'SPANK!' +age = age + 1 +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..1116f3722 100644 --- a/ch12-new-classes-of-objects/one_billion_seconds.rb +++ b/ch12-new-classes-of-objects/one_billion_seconds.rb @@ -1 +1 @@ -# your code here \ No newline at end of file +puts(Time.gm(1986, 3, 1, 11, 00) + 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..314c6c478 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,32 @@ 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} + 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')) From 9b6d8a18de5a5e307bc4c908a0d0811140fa3c77 Mon Sep 17 00:00:00 2001 From: stuartcooper Date: Thu, 8 Sep 2016 17:30:37 +0100 Subject: [PATCH 6/7] Adding Ch13 --- .../extend_built_in_classes.rb | 58 +++++++- .../interactive_baby_dragon.rb | 127 +++++++++++++++++- ch13-creating-new-classes/orange_tree.rb | 73 +++++++++- 3 files changed, 254 insertions(+), 4 deletions(-) diff --git a/ch13-creating-new-classes/extend_built_in_classes.rb b/ch13-creating-new-classes/extend_built_in_classes.rb index c3e793933..415e971af 100644 --- a/ch13-creating-new-classes/extend_built_in_classes.rb +++ b/ch13-creating-new-classes/extend_built_in_classes.rb @@ -1,3 +1,57 @@ +=begin +class Array + def shuffle + arr = self + + shuf = [] + #shuffle an array of any size above zero + while arr.length > 0 + rand_index = rand(arr.length) + #iterate each item placing all bar the random one in the new array which goes into shuf + 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 = curr_index + 1 + end + #call back new array instead of original array + arr = new_arr + end + + shuf + end +=end + 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 = roman + 'M' * (self / 1000) + roman = roman + 'D' * (self % 1000/ 500) + roman = roman + 'C' * (self % 500 / 100) + roman = roman + 'L' * (self % 100 / 50) + roman = roman + 'X' * (self % 50 / 10) + roman = roman + 'V' * (self % 10 / 5) + roman = roman + 'I' * (self % 5 / 1) + + roman + end +end + +puts [1, 2, 3, 4, 5].shuffle +puts 7.factorial +puts 112.to_roman diff --git a/ch13-creating-new-classes/interactive_baby_dragon.rb b/ch13-creating-new-classes/interactive_baby_dragon.rb index 801de24bd..a3114ab15 100644 --- a/ch13-creating-new-classes/interactive_baby_dragon.rb +++ b/ch13-creating-new-classes/interactive_baby_dragon.rb @@ -1 +1,126 @@ -# your code here \ No newline at end of file +class Dragon + def initialize name + @name = name + @asleep = false + @stuff_in_belly = 10 # 10 = full + @stuff_in_intestine = 0 # No need to go + + 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 = false + puts "#{@name} wakes up slowly." + end + end + + def toss + puts "You toss #{@name} up into the air." + puts 'They giggle and singe your eyebrows.' + passage_of_time + end + def rock + puts "You rock #{@name} gently." + @asleep = true + puts 'They briefly doze off...' + passage_of_time + if @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 the dragon but + #cannot ask if they are hungry.) + def hungry? + #Method names can end with ?, but this usually only for true/false returns + @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 'They wake up suddenly' + end + puts "#{@name} is starving! In desperation they ate YOU!" + exit + end + + if @stuff_in_intestine >= 10 + @stuff_in_intestine = 0 + puts "Whoops #{@name} had an accident..." + end + + if hungry? + if @asleep = false + puts 'They wake up suddenly!' + end + puts "#{@name}'s stomach grumbles..." + end + + if poopy? + if @asleep + @asleep = false + puts "They wake up suddenly!" + end + puts "#{@name} does the potty dance..." + end +end +end + +puts "What is the name of your dragon?" +name = gets.chomp +dragon = Dragon.new name + +while true + puts + puts 'Please choose a command for your dragon: feed, toss, walk, rock, put to bed, exit' + command = gets.chomp + + if command == 'exit' + exit + elsif command == 'feed' + dragon.feed + elsif command == 'toss' + dragon.toss + elsif command == 'walk' + dragon.walk + elsif command == 'rock' + dragon.rock + elsif command == 'put to bed' + dragon.put_to_bed + else + puts 'Command your dragon!' + end + end diff --git a/ch13-creating-new-classes/orange_tree.rb b/ch13-creating-new-classes/orange_tree.rb index 025d08907..9c0024ab3 100644 --- a/ch13-creating-new-classes/orange_tree.rb +++ b/ch13-creating-new-classes/orange_tree.rb @@ -7,5 +7,76 @@ class OrangeTree - # your code here + def initialize + @height = 0 + @count_the_oranges = 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 + @count_the_oranges + else + 'A dead tree has no oranges :(' + end + end + + def one_year_passes + if @alive + @height = @height + 0.4 + @count_the_oranges = 0 + if @height > 10 && rand(2) > 0 + @alive = false + 'Oh no! The tree is too old, and has died. :(' + elsif @height > 2 + @count_the_oranges = (@height * 15 - 25).to_i + "This year your tree grew to #{@height.round(1)}m tall," + + " and produced #{@count_the_oranges} 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 @count_the_oranges > 0 + '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) From 1fc8033df2669d0af3d985652fe8ec161c10919c Mon Sep 17 00:00:00 2001 From: stuartcooper Date: Fri, 9 Sep 2016 12:24:06 +0100 Subject: [PATCH 7/7] Adding Ch14 --- .../better_program_logger.rb | 31 +++++++++++++++++-- .../even_better_profiling.rb | 22 +++++++++++-- ch14-blocks-and-procs/grandfather_clock.rb | 20 ++++++++++-- ch14-blocks-and-procs/program_logger.rb | 18 +++++++++-- 4 files changed, 83 insertions(+), 8 deletions(-) diff --git a/ch14-blocks-and-procs/better_program_logger.rb b/ch14-blocks-and-procs/better_program_logger.rb index 0e2e18d57..010bf474d 100644 --- a/ch14-blocks-and-procs/better_program_logger.rb +++ b/ch14-blocks-and-procs/better_program_logger.rb @@ -1,3 +1,30 @@ +$logger_depth = 0 + def log desc, &block - # your code here -end \ No newline at end of file + 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 + +log 'outer block' do + log 'some little block' do + log 'teeny-tiny block' do + 'lOtS oF lOvE'.downcase +end + + 7 * 3 * 2 +end + +log 'yet another block' do + '!doof naidnI ekil 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..b56d9df82 100644 --- a/ch14-blocks-and-procs/even_better_profiling.rb +++ b/ch14-blocks-and-procs/even_better_profiling.rb @@ -1,3 +1,21 @@ def profile block_description, &block - # your code here -end \ No newline at end of file + profile_on = false + if profile_on + start_time = Time.new + block.call + duration = Time.new - start_time + puts "#{block_description}: #{duration} seconds" +else + block.call +end +end + +profile '10000 multiplications' do + number = 1 + + 10000.times do + number = number * 22 + end + + puts "#{number.to_s.length} digits" +end diff --git a/ch14-blocks-and-procs/grandfather_clock.rb b/ch14-blocks-and-procs/grandfather_clock.rb index 916f6d354..37c219a2c 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 = 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..7f32beddc 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 + puts 'Beginning "' + desc + '"...' + result = block.call + puts '..."' + desc + '" finished, returning: ' + result.to_s +end + +log 'outer block' do + log 'some little block' do + 1**1 + 2**2 +end + +log 'yet another block' do + '!doof iahT ekil I'.reverse +end + +'0' == 0 +end