From 8a6b4a0145ddd1f623e40d6c1fcd97d98d4f3dec Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Thu, 8 Sep 2016 12:10:58 +0100 Subject: [PATCH 01/14] updated ask.rb --- ch09-writing-your-own-methods/ask.rb | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/ch09-writing-your-own-methods/ask.rb b/ch09-writing-your-own-methods/ask.rb index 01716eb35..005ccf82c 100644 --- a/ch09-writing-your-own-methods/ask.rb +++ b/ch09-writing-your-own-methods/ask.rb @@ -1,3 +1,25 @@ 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 +end + + +puts 'Hello, and thank you for...' +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?' + +puts +puts 'DEBRIEFING' +puts 'Thank you for...' +puts +puts wets_bed From a29673c9c384141fef5799a40e7d582ba1eefa72 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Thu, 8 Sep 2016 13:55:44 +0100 Subject: [PATCH 02/14] old_school_roman_numerals --- .../old_school_roman_numerals.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) 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..dfe53c1c3 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,13 @@ def old_roman_numeral num # your code here -end \ No newline at end of file + +roman = '' + +roman << 'M'*(num /1000) +roman << 'D'*(num %1000 /500) +roman << 'C'*(num %500 /100) +roman << 'L'*(num %100 /50) +roman << 'X'*(num %50 /10) +roman << 'V'*(num %10 /5) +roman << 'I'*(num %5 /1) +end From e75bee7546e0c99c12617f16cdea7f59f0e6a581 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Thu, 8 Sep 2016 13:58:33 +0100 Subject: [PATCH 03/14] update old_school_roman_numerals --- ch09-writing-your-own-methods/old_school_roman_numerals.rb | 4 ++++ 1 file changed, 4 insertions(+) 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 dfe53c1c3..e17f81bcd 100644 --- a/ch09-writing-your-own-methods/old_school_roman_numerals.rb +++ b/ch09-writing-your-own-methods/old_school_roman_numerals.rb @@ -10,4 +10,8 @@ def old_roman_numeral num roman << 'X'*(num %50 /10) roman << 'V'*(num %10 /5) roman << 'I'*(num %5 /1) + +roman end + +puts old_roman_numeral(1991) From 6a1b29eff9b63e57dae456af85bf0eeae3e8036e Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Thu, 8 Sep 2016 14:32:30 +0100 Subject: [PATCH 04/14] added roman_numerals.rb --- .../roman_numerals.rb | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/ch09-writing-your-own-methods/roman_numerals.rb b/ch09-writing-your-own-methods/roman_numerals.rb index 5c93b59ac..2da19b2f7 100644 --- a/ch09-writing-your-own-methods/roman_numerals.rb +++ b/ch09-writing-your-own-methods/roman_numerals.rb @@ -1,3 +1,41 @@ 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 +ones = num % 10 / 1 + +roman = 'M' * thousand + if hundred ==9 + roman << 'CM' + elsif hundred == 4 + roman << 'CD' + else + roman << 'D' * (num %1000 /500) + roman << 'C' * (num %500 /100) + end + + if ten == 9 + roman << 'XC' + elsif ten == 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(1984) From 7a6de70b1f535ec7e782c068d02a27e4ca23e462 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Sun, 11 Sep 2016 16:11:58 +0100 Subject: [PATCH 05/14] rites_of_passage_sorting.rb --- ch10-nothing-new/rites_of_passage_sorting.rb | 29 ++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 ch10-nothing-new/rites_of_passage_sorting.rb diff --git a/ch10-nothing-new/rites_of_passage_sorting.rb b/ch10-nothing-new/rites_of_passage_sorting.rb new file mode 100644 index 000000000..4e882946f --- /dev/null +++ b/ch10-nothing-new/rites_of_passage_sorting.rb @@ -0,0 +1,29 @@ +def shuffle arr + # your code here + + def sort(some_array) + recursive_sort(some_array, []) + end + + def recursive_sort(unsorted_array, sorted_array) + if unsorted_array.length <=0 + return sorted_array + end + + smallest = unsorted.pop + still_unsorted =[] + + unsorted_array.each do |word| + if word < smallest + still_unsorted.push smallest + smallest = x + else + still_unsorted.push tested_object + end + end + + sorted.push smallest + + recursive_sort still_unsorted, sorted_array +end +puts(sort(['can','feel', 'like','singing','a', 'can'])) From f0df42b89b22535eca26cb8e47d1a2cbded215db Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Sun, 11 Sep 2016 16:15:05 +0100 Subject: [PATCH 06/14] shuffle.rb --- ch10-nothing-new/shuffle.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ch10-nothing-new/shuffle.rb b/ch10-nothing-new/shuffle.rb index a486ad94c..ab17c3c32 100644 --- a/ch10-nothing-new/shuffle.rb +++ b/ch10-nothing-new/shuffle.rb @@ -1,3 +1,4 @@ def shuffle arr - # your code here -end \ No newline at end of file + arr.sort_by{rand} +end +puts shuffle(['this', 'is', 'a','shuffle','test']) From e30744a8660833802b83e653d840e02ea7f12291 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Sun, 11 Sep 2016 16:21:45 +0100 Subject: [PATCH 07/14] delete --- ch10-nothing-new/rites_of_passage_sorting.rb | 29 -------------------- 1 file changed, 29 deletions(-) delete mode 100644 ch10-nothing-new/rites_of_passage_sorting.rb diff --git a/ch10-nothing-new/rites_of_passage_sorting.rb b/ch10-nothing-new/rites_of_passage_sorting.rb deleted file mode 100644 index 4e882946f..000000000 --- a/ch10-nothing-new/rites_of_passage_sorting.rb +++ /dev/null @@ -1,29 +0,0 @@ -def shuffle arr - # your code here - - def sort(some_array) - recursive_sort(some_array, []) - end - - def recursive_sort(unsorted_array, sorted_array) - if unsorted_array.length <=0 - return sorted_array - end - - smallest = unsorted.pop - still_unsorted =[] - - unsorted_array.each do |word| - if word < smallest - still_unsorted.push smallest - smallest = x - else - still_unsorted.push tested_object - end - end - - sorted.push smallest - - recursive_sort still_unsorted, sorted_array -end -puts(sort(['can','feel', 'like','singing','a', 'can'])) From ca0ec1897796f5d25f14a41f3d4d07038c0a6522 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Sun, 11 Sep 2016 16:30:09 +0100 Subject: [PATCH 08/14] sort.rb --- ch10-nothing-new/sort.rb | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/ch10-nothing-new/sort.rb b/ch10-nothing-new/sort.rb index 44c6deb58..a01a508c0 100644 --- a/ch10-nothing-new/sort.rb +++ b/ch10-nothing-new/sort.rb @@ -1,3 +1,25 @@ 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 + + smallest = unsorted.pop + still_unsorted = [] + + unsorted.each do |word| + if word < smallest + still_unsorted.push smallest + smallest = word + else + still_unsorted.push word + end + end + + sorted.push smallest + rec_sort still_unsorted, sorted +end +puts(sort(['can','feel','singing','like','a','can'])) From 03e1a0d1ee78f964ef7a444876f71fcb015e38bd Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Sun, 11 Sep 2016 16:34:23 +0100 Subject: [PATCH 09/14] dictionary sort --- ch10-nothing-new/dictionary_sort.rb | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/ch10-nothing-new/dictionary_sort.rb b/ch10-nothing-new/dictionary_sort.rb index c9893d0fd..1ac08e3a1 100644 --- a/ch10-nothing-new/dictionary_sort.rb +++ b/ch10-nothing-new/dictionary_sort.rb @@ -1,3 +1,26 @@ def dictionary_sort arr - # your code here -end \ No newline at end of file + rec_dict_sort arr,[] +end + +def rec_dict_sort unsorted_array, sorted_array + if unsorted_array.length <=0 + return sorted_array + end + + smallest = unsorted_array.pop + still_unsorted = [] + + unsorted_array.each do |word| + if word.downcase < smallest.downcase + still_unsorted.push smallest + smallest = word + else + still_unsorted.push word + end + end + + sorted_array.push smallest + rec_dict_sort still_unsorted, sorted_array +end + +puts(dictionary_sort(['can','feel','like','singing','A','can'])) From f3b596516e90570ff1fb33048d98b8c69308eb50 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Mon, 12 Sep 2016 09:42:36 +0100 Subject: [PATCH 10/14] english_number.rb --- ch10-nothing-new/english_number.rb | 63 +++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/ch10-nothing-new/english_number.rb b/ch10-nothing-new/english_number.rb index c0129bc4e..6c8cb5bfe 100644 --- a/ch10-nothing-new/english_number.rb +++ b/ch10-nothing-new/english_number.rb @@ -1,3 +1,64 @@ 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','fourty','fifty','sixty','seventy','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',39], +['duodecillion',39],['tredecillion',42],['quattuordecillion',45],['quindecillion',48], +['sexdecillion',51],['septendectillion',54],['octodecillion',57],['novemdecillion',60], +['vigintillion',63],['googol',100]] + +#'left' is how much left of the number we still have t write +#'write' is the part we are writing out right now + +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 + +write = left/10 +left = left -write*10 + +if write >0 + if write ((write ==1) and (left >0)) + num_string =num_string + teenagers[left-1] + left =0 + else + num_string = num_string + tens_place[write-1] + end +end + +write=left +left=0 +if write >0 + num_string = num_string+ones_place[write-1] +end + +num_string +end + +puts english_number(999) +puts english_number(4352) From 34633449d19323e6352f5e7b479231544009535e Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Mon, 12 Sep 2016 09:52:38 +0100 Subject: [PATCH 11/14] ch11 --- .../ninety_nine_bottles_of_beer.rb | 76 +++++++++++++- .../build_a_better_playlist.rb | 57 ++++++++++- .../build_your_own_playlist.rb | 10 +- .../safer_picture_downloading.rb | 99 ++++++++++++++++++- 4 files changed, 238 insertions(+), 4 deletions(-) diff --git a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb index 801de24bd..db29a1c99 100644 --- a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb +++ b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb @@ -1 +1,75 @@ -# your code here \ No newline at end of file +# your code heredef 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','fourty','fifty','sixty','seventy','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',39], +['duodecillion',39],['tredecillion',42],['quattuordecillion',45],['quindecillion',48], +['sexdecillion',51],['septendectillion',54],['octodecillion',57],['novemdecillion',60], +['vigintillion',63],['googol',100]] + +#'left' is how much left of the number we still have t write +#'write' is the part we are writing out right now + +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 + +write = left/10 +left = left -write*10 + +if write >0 + if write ((write ==1) and (left >0)) + num_string =num_string + teenagers[left-1] + left =0 + else + num_string = num_string + tens_place[write-1] + end +end + +write=left +left=0 +if write >0 + num_string = num_string+ones_place[write-1] +end + +num_string +end + +num_at_start = 5 +num_now = num_at_start +while num_now >2 + puts enlgish_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 + puts "Two bottles of beer on the wall, two bottles of beer!" + puts "Take one down, pass it around, one bottle of beer on the wall!" + puts "One bottle of beer on the wall, one bottle of beer!" + puts "take one down, pass it around, no more bottles of beer on the wall!" diff --git a/ch11-reading-and-writing/build_a_better_playlist.rb b/ch11-reading-and-writing/build_a_better_playlist.rb index 3b31bd241..dba748318 100644 --- a/ch11-reading-and-writing/build_a_better_playlist.rb +++ b/ch11-reading-and-writing/build_a_better_playlist.rb @@ -1,3 +1,58 @@ def music_shuffle filenames - # your code here + songs_and_paths = filenames.map do |s| + [s, s.split('/')] # [song, path] + end + + tree = {:root => []} + + # put each song into the tree + insert_into_tree = proc do |branch, song, path| + if path.length == 0 # add to current branch + branch[:root] << song + else # delve deeper + sub_branch = path[0] + path.shift # like "pop", but pops off the front + + if !branch[sub_branch] + branch[sub_branch] = {:root => []} + end + + insert_into_tree[branch[sub_branch], song, path] + end + end + + songs_and_paths.each{|sp| insert_into_tree[tree, *sp]} + + # recursively: + # - shuffle sub-branches (and root) + # - weight each sub-branch (and root) + # - merge (shuffle) these groups together + shuffle_branch = proc do |branch| + shuffled_subs = [] + + branch.each do |key, unshuffled| + shuffled_subs << if key == :root + unshuffled # At this level, these are all duplicates. + else + shuffle_branch[unshuffled] + end + end + + weighted_songs = [] + + shuffled_subs.each do |shuffled_songs| + shuffled_songs.each_with_index do |song, idx| + num = shuffled_songs.length.to_f + weight = (idx + rand) / num + weighted_songs << [song, weight] + end + end + + weighted_songs.sort_by{|s,v| v}.map{|s,v| s} + end + shuffle_branch[tree] 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..99195678e 100644 --- a/ch11-reading-and-writing/build_your_own_playlist.rb +++ b/ch11-reading-and-writing/build_your_own_playlist.rb @@ -1 +1,9 @@ -# 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 'Done!' diff --git a/ch11-reading-and-writing/safer_picture_downloading.rb b/ch11-reading-and-writing/safer_picture_downloading.rb index 801de24bd..8ca1f9180 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 +# your code here# 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\Anna\Desktop\Dropbox\picture' + +# 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 f9f5342414fd3b0cd4d44ed97167209f345a07d1 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Mon, 12 Sep 2016 09:54:39 +0100 Subject: [PATCH 12/14] ch12 --- .../birthday_helper.rb | 29 +++++++++++++++- ch12-new-classes-of-objects/happy_birthday.rb | 19 ++++++++++- .../one_billion_seconds.rb | 2 +- ...party_like_its_roman_to_integer_mcmxcix.rb | 33 +++++++++++++++++-- 4 files changed, 78 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..1d809aefc 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.readlines('birthdates.txt').each do |line| + name, date, year = line.split(',') + birth_dates[name] = Time.gm(year, *(date.split)) +end + +puts 'Whose birthday would you like to know?' +name = gets.chomp +bday = birth_dates[name] + +if bday == nil + puts "Oooh, I don't know that one..." +else + now = Time.new + age = now.year - bday.year + + if now.month > bday.month || (now.month == bday.month && now.day > bday.day) + age += 1 + end + + if now.month == bday.month && now.day == bday.day + puts "#{name} turns #{age} TODAY!!" + else + date = bday.strftime "%b %d" + puts "#{name} will be #{age} on #{date}." + end +end diff --git a/ch12-new-classes-of-objects/happy_birthday.rb b/ch12-new-classes-of-objects/happy_birthday.rb index 801de24bd..7d43b7ef7 100644 --- a/ch12-new-classes-of-objects/happy_birthday.rb +++ b/ch12-new-classes-of-objects/happy_birthday.rb @@ -1 +1,18 @@ -# your code here \ No newline at end of file +puts 'What year were you born?' +b_year = gets.chomp.to_i + +puts 'What month were you born? (1-12)' +b_month = gets.chomp.to_i + +puts 'What day of the month were you born?' +b_day = gets.chomp.to_i + +b = Time.local(b_year, b_month, b_day) +t = Time.new + +age = 1 + +while Time.local(b_year + age, b_month, b_day) <= t + 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..15e4a71e9 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(1976, 8, 3, 13, 31) + 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..bc0107107 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 + roman.reverse.each_char do |c_or_C| + c = c_or_C.downcase + val = digit_vals[c] + if !val + puts 'This is not a valid roman numeral!' + return + end + + if val < prev + val *= -1 + else + prev = val + end + + total += val + end + + total +end + +puts(roman_to_integer('mcmxcix')) +puts(roman_to_integer('CCCLXV')) From e99ee963d879b6eb0184c916c335eca2d8d0cc03 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Mon, 12 Sep 2016 09:58:44 +0100 Subject: [PATCH 13/14] ch13 --- .../extend_built_in_classes.rb | 29 +++++++++- .../interactive_baby_dragon.rb | 27 ++++++++- ch13-creating-new-classes/orange_tree.rb | 58 ++++++++++++++++++- 3 files changed, 110 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..7ac0b5ef8 100644 --- a/ch13-creating-new-classes/extend_built_in_classes.rb +++ b/ch13-creating-new-classes/extend_built_in_classes.rb @@ -1,3 +1,28 @@ +class Array + def shuffle + sort_by{rand} + end +end + + 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 + + raise 'Must use positive integer' if self <= 0 + 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) + roman + end +end + +p 7.factorial.to_roman.split(//).shuffle diff --git a/ch13-creating-new-classes/interactive_baby_dragon.rb b/ch13-creating-new-classes/interactive_baby_dragon.rb index 801de24bd..e66d66bf0 100644 --- a/ch13-creating-new-classes/interactive_baby_dragon.rb +++ b/ch13-creating-new-classes/interactive_baby_dragon.rb @@ -1 +1,26 @@ -# your code here \ No newline at end of file + +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..fd5d49af9 100644 --- a/ch13-creating-new-classes/orange_tree.rb +++ b/ch13-creating-new-classes/orange_tree.rb @@ -6,6 +6,62 @@ # check out the rspec spec/ch13/orange_tree_spec.rb to see what strings we're looking for in the responses. + class OrangeTree - # your code here + 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 && rand(2) > 0 + # 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 From 1a92dd5746faacc199273ac1c5541498ce0795d2 Mon Sep 17 00:00:00 2001 From: Anna Beddow Date: Mon, 12 Sep 2016 10:00:46 +0100 Subject: [PATCH 14/14] ch14 --- .../better_program_logger.rb | 31 +++++++++++++++++-- .../even_better_profiling.rb | 15 +++++++-- ch14-blocks-and-procs/grandfather_clock.rb | 19 ++++++++++-- ch14-blocks-and-procs/program_logger.rb | 18 +++++++++-- 4 files changed, 75 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..80f61e677 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 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..3c8b429c0 100644 --- a/ch14-blocks-and-procs/even_better_profiling.rb +++ b/ch14-blocks-and-procs/even_better_profiling.rb @@ -1,3 +1,14 @@ def profile block_description, &block - # your code here -end \ No newline at end of file + # To turn profiling on/off, set this + # to true/false. + 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..545407178 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..559789486 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