From d0ad2770a4cb80b46267ecf28f19ed41684e015b Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Wed, 7 Sep 2016 19:35:56 +0300 Subject: [PATCH 01/24] Chapter 9. excercise 1: ASK --- ch09-writing-your-own-methods/ask.rb | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/ch09-writing-your-own-methods/ask.rb b/ch09-writing-your-own-methods/ask.rb index 01716eb35..cfacfd7a2 100644 --- a/ch09-writing-your-own-methods/ask.rb +++ b/ch09-writing-your-own-methods/ask.rb @@ -1,3 +1,13 @@ -def ask question - # your code here +def ask question + + while true + puts question + reply = gets.chomp.downcase + + if (reply == 'yes' || reply == 'no') + return reply == 'yes' + else + puts 'Please answer "yes" or "no".' + end + end end \ No newline at end of file From f3ef8bfc6c537f2ad74101e2f2549e7089783d3d Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Wed, 7 Sep 2016 19:47:42 +0300 Subject: [PATCH 02/24] Chapter 9. Old school Romans --- .../old_school_roman_numerals.rb | 16 +++++++++++++++- 1 file changed, 15 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..0bd17ca2a 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,17 @@ def old_roman_numeral num - # your code here + romans = ['I', 'V', 'X', 'L', 'C', 'D', 'M'] + values = [ 1, 5, 10, 50, 100, 500, 1000 ] + result = '' + + values.select!{ |v| v <= num } + + (values.length-1).downto(0) { |i| + max_num = values[i] + (num / max_num).times { + result += romans[i] + num -= max_num + } + } + + return result end \ No newline at end of file From 2f6d4849a949342be18248475d651738bba0491b Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Wed, 7 Sep 2016 23:24:43 +0300 Subject: [PATCH 03/24] Chapter 9. Roman numbers. complex refactoring :) --- .../roman_numerals.rb | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/ch09-writing-your-own-methods/roman_numerals.rb b/ch09-writing-your-own-methods/roman_numerals.rb index 5c93b59ac..09bbc0b38 100644 --- a/ch09-writing-your-own-methods/roman_numerals.rb +++ b/ch09-writing-your-own-methods/roman_numerals.rb @@ -1,3 +1,20 @@ def roman_numeral num - # your code here + roman_letters = "IVXLCDM" + mods = {:C => 100, :X => 10, :I => 1} + + roman = 'M' * (num / 1000) + + mods.each do |k, v| + digit = num % (10 * v) / v + id = roman_letters.index(k.to_s) + + if (digit == 9) || (digit == 4) + roman += k.to_s + (digit == 9 ? roman_letters[id+2] : roman_letters[id+1]) + else + roman += roman_letters[id+1] * (num % (10 * v) / (5 * v)) + roman += roman_letters[id] * (num % (5 * v) / v) + end + end + + roman end \ No newline at end of file From 7008ee3021b47e1a9c3a4190e72bd4df1b3fe648 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Thu, 8 Sep 2016 11:19:03 +0300 Subject: [PATCH 04/24] Chapter 10. Shuffle method --- ch10-nothing-new/shuffle.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ch10-nothing-new/shuffle.rb b/ch10-nothing-new/shuffle.rb index a486ad94c..212539eae 100644 --- a/ch10-nothing-new/shuffle.rb +++ b/ch10-nothing-new/shuffle.rb @@ -1,3 +1,5 @@ def shuffle arr - # your code here + arr.shuffle! + half = arr.length / 2 + arr = arr.slice(0, half).shuffle + arr.slice(half, arr.length).shuffle end \ No newline at end of file From a87d1c747a74dafd1d4c098aa62a158f1d5ad291 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Thu, 8 Sep 2016 11:27:14 +0300 Subject: [PATCH 05/24] Chapter 10. Dictionary sort --- ch10-nothing-new/dictionary_sort.rb | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/ch10-nothing-new/dictionary_sort.rb b/ch10-nothing-new/dictionary_sort.rb index c9893d0fd..a5fa81fbd 100644 --- a/ch10-nothing-new/dictionary_sort.rb +++ b/ch10-nothing-new/dictionary_sort.rb @@ -1,3 +1,22 @@ def dictionary_sort arr - # your code here + recursive_sort arr, [] +end + +def recursive_sort unsorted_array, sorted_array + smallest_id = 0 + + (unsorted_array.length-1).times { |i| + if unsorted_array[smallest_id].downcase > unsorted_array[i+1].downcase + smallest_id = i+1 + end + } + + sorted_array.push(unsorted_array[smallest_id]) + unsorted_array.delete_at(smallest_id) + + if unsorted_array.length > 0 + recursive_sort unsorted_array, sorted_array + else + return sorted_array + end end \ No newline at end of file From b969da9ea816dc55ab00cb0f5cb40692635cec88 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Thu, 8 Sep 2016 13:33:42 +0300 Subject: [PATCH 06/24] Chapter 10. quindecillion... --- ch10-nothing-new/english_number.rb | 69 +++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 2 deletions(-) diff --git a/ch10-nothing-new/english_number.rb b/ch10-nothing-new/english_number.rb index c0129bc4e..a1b9eeeb0 100644 --- a/ch10-nothing-new/english_number.rb +++ b/ch10-nothing-new/english_number.rb @@ -1,3 +1,68 @@ def english_number number - # your code here -end + if number < 0 + return 'Please enter a number that isn\'t negative.' + elsif 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'] + + big_numbers = { :quindecillion => 10**48, :quattuordecillion => 10**45, :tredecillion => 10**42, + :duodecillion => 10**39, :undecillion => 10**36, :decillion => 10**33, + :nonillion => 10**30, :octillion => 10**27, :septillion => 10**24, + :sextillion => 10**21, :quintillion => 10**18, :quadrillion => 10**15, + :trillion => 10**12, :billion => 10**9, :million => 1_000_000, + :thousand => 1000, :hundred => 100 } + + left = number + + big_numbers.each do |word, num| + write = left / num + left = left - write * num + + if write > 0 + numbers = english_number write + num_string = num_string + numbers + " #{word}" + + if left > 0 + 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" + 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 + '-' # So we don't write 'sixtyfour'... + 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] + end + + num_string +end \ No newline at end of file From 0071f24fcca7a660230aff9d7fa2bd63998c61d6 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Thu, 8 Sep 2016 19:01:41 +0300 Subject: [PATCH 07/24] Chapter 10. 99 bottles of beer... --- ch10-nothing-new/ninety_nine_bottles_of_beer.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb index 801de24bd..8e73fc611 100644 --- a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb +++ b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb @@ -1 +1,11 @@ -# your code here \ No newline at end of file +load 'english_number.rb' + +num_at_start = 21 # change to 9999 if you want + +num_at_start.downto(1) do |num_now| + puts english_number(num_now).capitalize + " bottle#{num_now==1 ? '' : 's'} of beer on the wall, " + + english_number(num_now) + " bottle#{num_now==1 ? '' : 's'} of beer!" + + puts "Take one down, pass it around, " + + (num_now == 1 ? 'no more' : english_number(num_now-1)) + " bottle#{num_now == 2 ? '' : 's'} of beer on the wall!" +end \ No newline at end of file From ad957b151aadb07e6c9123a837f9a660d5fa08fb Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Thu, 8 Sep 2016 19:35:10 +0300 Subject: [PATCH 08/24] Chapter 10. recursive sort --- ch10-nothing-new/sort.rb | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/ch10-nothing-new/sort.rb b/ch10-nothing-new/sort.rb index 44c6deb58..de50ce765 100644 --- a/ch10-nothing-new/sort.rb +++ b/ch10-nothing-new/sort.rb @@ -1,3 +1,19 @@ def sort arr - # your code here + recursive_sort arr, [] +end + +def recursive_sort unsorted_array, sorted_array + smallest_id = 0 + + (unsorted_array.length-1).times { |i| + smallest_id = i+1 if unsorted_array[smallest_id] > unsorted_array[i+1] + } + + sorted_array.push(unsorted_array.delete_at(smallest_id)) + + if unsorted_array.length > 0 + recursive_sort unsorted_array, sorted_array + else + return sorted_array + end end \ No newline at end of file From 5ac3e3251d6e39797408cd6258f94e840efb3f07 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Fri, 9 Sep 2016 11:16:17 +0300 Subject: [PATCH 09/24] Chapter 11. safer picture downloading --- .../safer_picture_downloading.rb | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/ch11-reading-and-writing/safer_picture_downloading.rb b/ch11-reading-and-writing/safer_picture_downloading.rb index 801de24bd..287e76b0f 100644 --- a/ch11-reading-and-writing/safer_picture_downloading.rb +++ b/ch11-reading-and-writing/safer_picture_downloading.rb @@ -1 +1,38 @@ -# your code here \ No newline at end of file +# This program safely copies all .jpg from current directory to a chosen image_path +image_path = './PictureInbox' +if Dir[image_path].empty? + Dir.mkdir(image_path) +end +Dir.chdir(image_path) + +# First we find all of the pictures to be moved. +pic_names = Dir['../*.jpg'] + +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 '.' # This is our "progress bar". + new_name = if pic_number < 10 + "#{batch_name}0#{pic_number}.jpg" + else + "#{batch_name}#{pic_number}.jpg" + end + + + if !File.exist?(new_name) + File.rename name, new_name + pic_number = pic_number + 1 + else + puts "\n\n" + puts "ERROR! File '#{new_name}' already exists in #{Dir.pwd}" + exit + end +end + +puts +puts 'Done!' \ No newline at end of file From 2f852a8627c5c17b10eb5d91b6030110bbb1ecac Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Fri, 9 Sep 2016 13:20:01 +0300 Subject: [PATCH 10/24] Chapter 11. Build my own playlist --- .../build_your_own_playlist.rb | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/ch11-reading-and-writing/build_your_own_playlist.rb b/ch11-reading-and-writing/build_your_own_playlist.rb index 801de24bd..68b3f9eb0 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 +# This program finds all music files (.mp3, .wav, .aif) +# in your chosen directory - 'MUSIC_PATH', +# and makes a .m3u playlist from it. +# Tracks are sorted alphabetically + +MUSIC_PATH = '/Users/tadasmajeris/Downloads/nu house : techno' + +if Dir[MUSIC_PATH].empty? + puts "ERROR! Directory '#{MUSIC_PATH}' not found!" + exit +end +Dir.chdir(MUSIC_PATH) + +# First we find all of the pictures to be moved. +file_names = Dir['./*.{mp3,wav,aif}'] + +if file_names.length == 0 + puts "ERROR! Directory '#{MUSIC_PATH}' is empty!" + exit +end +file_names.sort! # sort alphabetically, as it first finds .mp3, then .wav + +puts 'What would you like to call this playlist?' +playlist_name = '' +until playlist_name != '' + playlist_name = gets.chomp.strip + puts 'Please, enter a name' if playlist_name == '' +end +playlist_name += '.m3u' + +playlist_text = "" +file_names.each { |name| playlist_text << name + "\n" } + +File.open playlist_name, 'w' do |f| + f.write playlist_text +end + +puts +puts 'Done!' \ No newline at end of file From ce0971c8d44a763975ae0d0bcc1e14f14a0b9076 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Fri, 9 Sep 2016 15:20:04 +0300 Subject: [PATCH 11/24] Chapter 11. FIX: build your own playlist now searches the subdirectories too --- ch11-reading-and-writing/build_your_own_playlist.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ch11-reading-and-writing/build_your_own_playlist.rb b/ch11-reading-and-writing/build_your_own_playlist.rb index 68b3f9eb0..45cafc622 100644 --- a/ch11-reading-and-writing/build_your_own_playlist.rb +++ b/ch11-reading-and-writing/build_your_own_playlist.rb @@ -3,7 +3,7 @@ # and makes a .m3u playlist from it. # Tracks are sorted alphabetically -MUSIC_PATH = '/Users/tadasmajeris/Downloads/nu house : techno' +MUSIC_PATH = '/Users/tadasmajeris/Downloads/nu electro' if Dir[MUSIC_PATH].empty? puts "ERROR! Directory '#{MUSIC_PATH}' not found!" @@ -12,7 +12,7 @@ Dir.chdir(MUSIC_PATH) # First we find all of the pictures to be moved. -file_names = Dir['./*.{mp3,wav,aif}'] +file_names = Dir['./*/*.{mp3,wav,aif}'] if file_names.length == 0 puts "ERROR! Directory '#{MUSIC_PATH}' is empty!" From 5366fc837ad311f63acbc38fccc3249c32dc0bd6 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Fri, 9 Sep 2016 20:23:44 +0300 Subject: [PATCH 12/24] Small typo from last fix --- ch11-reading-and-writing/build_your_own_playlist.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ch11-reading-and-writing/build_your_own_playlist.rb b/ch11-reading-and-writing/build_your_own_playlist.rb index 45cafc622..bfbd649fd 100644 --- a/ch11-reading-and-writing/build_your_own_playlist.rb +++ b/ch11-reading-and-writing/build_your_own_playlist.rb @@ -11,8 +11,8 @@ end Dir.chdir(MUSIC_PATH) -# First we find all of the pictures to be moved. -file_names = Dir['./*/*.{mp3,wav,aif}'] +# First we find all of the tracks to be moved. +file_names = Dir['./**/*.{mp3,wav,aif}'] if file_names.length == 0 puts "ERROR! Directory '#{MUSIC_PATH}' is empty!" From 24e2a9431c7457d9bb16bb25c6919f199cab56cc Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Fri, 9 Sep 2016 20:26:00 +0300 Subject: [PATCH 13/24] Chapter 11. Build better playlist &&& much nicer to read code! Yours trully, Mr.OOP --- .../build_a_better_playlist.rb | 93 ++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/ch11-reading-and-writing/build_a_better_playlist.rb b/ch11-reading-and-writing/build_a_better_playlist.rb index 3b31bd241..363fe5c40 100644 --- a/ch11-reading-and-writing/build_a_better_playlist.rb +++ b/ch11-reading-and-writing/build_a_better_playlist.rb @@ -1,3 +1,94 @@ +# This program finds all music files (.mp3, .wav, .aif) +# in your chosen directory - 'MUSIC_PATH', +# and makes a SHUFFLED .m3u playlist. +def shuffle arr + arr.shuffle! + half = arr.length / 2 + arr = arr.slice(0, half).shuffle + arr.slice(half, arr.length).shuffle +end + def music_shuffle filenames - # your code here + filenames_arr = [] + files_by_dir = {} + + filenames.each do |name| + dir_name = name.split('/')[0...-1].join('/') #[0...-1] all but last element (/filename.xxx) + + # create a hash, where key is directory name, and value is array of files in that dir.. + files_by_dir[dir_name] ||= [] + files_by_dir[dir_name] << name + end + + # shuffle files in each directory + files_by_dir.each { |dir, arr| arr = shuffle(arr) } + + new_list = [] + filenames.length.times do |i| + # take one item from each shuffled directory + files_by_dir.each do |dir, arr| + if !arr.empty? + # and add it to the new list // first or last item for more variety + new_list.push( (i%2==0) ? arr.shift : arr.pop ) + else + files_by_dir[dir].clear + end + end + end + + new_list +end + +def get_playlist_name + puts 'What would you like to call this playlist?' + playlist_name = '' + until playlist_name != '' + playlist_name = gets.chomp.strip + puts 'Please, enter a name' if playlist_name == '' + end + playlist_name = playlist_name + '.m3u' +end + +def get_file_names path + file_names = Dir['./**/*.{mp3,wav,aif,aiff,m4a}'] + + if file_names.length == 0 + puts "ERROR! Directory '#{path}' is empty!" + exit + end + file_names.sort! # sort alphabetically, as it first adds .mp3, then .wav and so on.. +end + +def change_dir_to path + if Dir[path].empty? + puts "ERROR! Directory '#{path}' not found!" + exit + end + Dir.chdir(path) +end + +def make_playlist(playlist_name, files) + playlist_text = "" + files.each { |name| playlist_text << name + "\n" } + + File.open playlist_name, 'w' do |f| + f.write playlist_text + end + + puts + puts 'Done!' end + +#--------------------------- PROGRAM ---------------------------# +MUSIC_PATH = '/Users/tadasmajeris/Music/GROSIU/- deep : house -' + +# Find if given path exists, change working directory to it +change_dir_to MUSIC_PATH + +# Find all of the tracks to be moved and shuffle them +file_names = music_shuffle(get_file_names MUSIC_PATH) + +# Get user to enter the playlist name +playlist_name = get_playlist_name + +# Make the playlist, save it to .m3u +make_playlist(playlist_name, file_names) \ No newline at end of file From ba6fbbb2cc73edcde90dad0da4168173e14c60e0 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Sat, 10 Sep 2016 16:00:56 +0200 Subject: [PATCH 14/24] Chapter 12. One billion seconds is soon.. --- ch12-new-classes-of-objects/one_billion_seconds.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ch12-new-classes-of-objects/one_billion_seconds.rb b/ch12-new-classes-of-objects/one_billion_seconds.rb index 801de24bd..ac8520db2 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 +bday = Time.gm(1986, 5, 21) +puts Time.at(bday.to_i + 10**9) From 9ac41882775706130652b70f2a7b18384b5a139f Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Sat, 10 Sep 2016 16:24:36 +0200 Subject: [PATCH 15/24] Chapter 12. Happy BDAY, SPANK --- ch12-new-classes-of-objects/happy_birthday.rb | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/ch12-new-classes-of-objects/happy_birthday.rb b/ch12-new-classes-of-objects/happy_birthday.rb index 801de24bd..aaeb1b8ac 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 +while true + puts "Enter your birthday in format: DD/MM/YYYY" + bday_arr = gets.chomp.strip.split('/') + day = bday_arr[0].to_i + mon = bday_arr[1].to_i + yea = bday_arr[2].to_i + if (1..31).include?(day) && (1..12).include?(mon) && (1900..Time.now.year).include?(yea) + bday = Time.gm(yea, mon, day) + break + else + puts "ERROR: Your entered date is wrong" + end +end + +age = Time.now.year - bday.year +age -= 1 if Time.now < bday + age + +puts "-" * 20 +puts "Your age is: #{age}" +puts "SPANK! " * age \ No newline at end of file From ca714d224ce3ae9e5262f546901e05c16b80f14a Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Sun, 11 Sep 2016 20:03:59 +0100 Subject: [PATCH 16/24] Chapter 12. Party like its roman integerrr --- ...party_like_its_roman_to_integer_mcmxcix.rb | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) 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..b8dfa5b2e 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,21 @@ def roman_to_integer roman - # your code here + @romans = { 'I' => 1, + 'V' => 5, + 'X' => 10, + 'L' => 50, + 'C' => 100, + 'D' => 500, + 'M' => 1000 } + + str = roman.upcase.reverse # we will go backwards + last_value = @romans[str[0]] # last digit's value + sum = last_value + + (1..str.length-1).each do |i| + next_value = @romans[str[i]] + sum += (next_value < last_value ? -1 : 1) * next_value # only two cases for -1, such as IV or IX.. + last_value = next_value + end + + sum end \ No newline at end of file From 27128c4a9632a165aaa92e619da681174b629419 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Sun, 11 Sep 2016 21:19:06 +0100 Subject: [PATCH 17/24] Chapter 12. Birthday helper. John and Yoko... --- ch12-new-classes-of-objects/bdays.txt | 4 ++ .../birthday_helper.rb | 49 ++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 ch12-new-classes-of-objects/bdays.txt diff --git a/ch12-new-classes-of-objects/bdays.txt b/ch12-new-classes-of-objects/bdays.txt new file mode 100644 index 000000000..d5c1469db --- /dev/null +++ b/ch12-new-classes-of-objects/bdays.txt @@ -0,0 +1,4 @@ +Alice Winters, Jan 5, 1989 +Tadas Majeris, May 21, 1986 +John Lennon, Oct 9, 1940 +Yoko Ono, Feb 18, 1933 diff --git a/ch12-new-classes-of-objects/birthday_helper.rb b/ch12-new-classes-of-objects/birthday_helper.rb index 801de24bd..7c77c6eff 100644 --- a/ch12-new-classes-of-objects/birthday_helper.rb +++ b/ch12-new-classes-of-objects/birthday_helper.rb @@ -1 +1,48 @@ -# your code here \ No newline at end of file +#make a hash of bdays (name as key, date as value) +#ask user to input a name +#tell when next bday will be + +@filepath = "bdays.txt" + +def read_bdays + hash = {} + file = File.open(@filepath, 'r') + file.each_line do |line| + # this regex finds first comma and optional spaces after, splits into 2 + name, date = line.chomp.split(/\,\W*/, 2) + date, year = date.split(/\,\W*/, 2) + month, day = date.split(/\W+/, 2) + hash[name] = [year, month, day] + end + return hash +end + +## program ## +if File.exist?(@filepath) + bdays = read_bdays + + print "Enter name: " + input = gets.chomp.strip.downcase + found = bdays.select do |name, v| + name.downcase.include?(input) + end + if found.empty? + puts "-" * 40 + puts "No results.\n\n" + else + puts "-" * 40 + now = Time.now + + found.each do |k, v| + bday = Time.gm(v[0], v[1], v[2]) + + #next year? - not (0), yes (1) + if_next_year = now.month < bday.month ? 0 : (now.month > bday.month) ? 1 : (now.day > bday.day ? 1 : 0) + next_bday = [now.year+if_next_year, bday.month, bday.day] + puts "#{k} next birthday:\t#{next_bday.join(', ')}.\tAge: #{next_bday[0]-bday.year}\n\n" + end + end + +else + puts "---> File '#{@filepath}' not found. Can't run the program.\n\n" +end \ No newline at end of file From 5e6ce20a96cb96694d765eb4ecf809f84c7ed37d Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Sun, 11 Sep 2016 21:37:54 +0100 Subject: [PATCH 18/24] Chapter 13. Extended Integer class --- .../extend_built_in_classes.rb | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/ch13-creating-new-classes/extend_built_in_classes.rb b/ch13-creating-new-classes/extend_built_in_classes.rb index c3e793933..1c941b788 100644 --- a/ch13-creating-new-classes/extend_built_in_classes.rb +++ b/ch13-creating-new-classes/extend_built_in_classes.rb @@ -1,3 +1,26 @@ class Integer - # your code here + + def to_roman + romans = ['I', 'V', 'X', 'L', 'C', 'D', 'M'] + values = [ 1, 5, 10, 50, 100, 500, 1000 ] + result = '' + num = self + + values.select!{ |v| v <= num } + + (values.length-1).downto(0) { |i| + max_num = values[i] + (num / max_num).times { + result += romans[i] + num -= max_num + } + } + + result + end + + def factorial(num=self) + raise 'You can\'t take the factorial of a negative number!' if num < 0 + num <= 1 ? 1 : num * factorial(num-1) + end end \ No newline at end of file From 16691252819acd0d58e219ad4adf1d52df336dd3 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Sun, 11 Sep 2016 22:38:26 +0100 Subject: [PATCH 19/24] Chapter 13. Interactive baby... --- .../interactive_baby_dragon.rb | 159 +++++++++++++++++- 1 file changed, 158 insertions(+), 1 deletion(-) diff --git a/ch13-creating-new-classes/interactive_baby_dragon.rb b/ch13-creating-new-classes/interactive_baby_dragon.rb index 801de24bd..5ddc68ce1 100644 --- a/ch13-creating-new-classes/interactive_baby_dragon.rb +++ b/ch13-creating-new-classes/interactive_baby_dragon.rb @@ -1 +1,158 @@ -# 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. + @actions = ['feed', 'walk', 'toss', 'sleep', 'rock', 'quit'] + + print_line + puts "#{@name} is born." + end + + def action_time! + display_actions + get_action + end + + def print_line + puts "-" * 45 + end + + def feed + print_line + puts "You feed #{@name}." + @stuff_in_belly = 10 + passage_of_time + action_time! + end + + def walk + print_line + puts "You walk #{@name}." + @stuff_in_intestine = 0 + passage_of_time + action_time! + end + + def sleep + print_line + 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 + + action_time! + end + + def toss + print_line + puts "You toss #{@name} up into the air." + puts 'He giggles, which singes your eyebrows.' + passage_of_time + action_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 + action_time! + end + + def quit + print_line + puts "Thanks for playing!" + exit + end + + def display_actions + puts + puts "Actions: #{@actions.join(', ')}" + end + + def get_action + while true + action = gets.chomp.strip.downcase + if @actions.include?(action) + dispatch(action) + break + else + display_actions + end + end + end + + private + + def dispatch action + puts + self.send(action) + end + + def hungry? + @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!' + 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 + end +end + +puts "Enter a name for your pet DRAGON:" +name = gets.chomp.strip.upcase +pet = Dragon.new name + +pet.action_time! \ No newline at end of file From ff02e9667d2e7c4760f17da8ea3075e23658a46b Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Sun, 11 Sep 2016 23:28:19 +0100 Subject: [PATCH 20/24] Chapter 13. Orange treeeee --- ch13-creating-new-classes/orange_tree.rb | 61 +++++++++++++++++++++++- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/ch13-creating-new-classes/orange_tree.rb b/ch13-creating-new-classes/orange_tree.rb index 025d08907..23173d57b 100644 --- a/ch13-creating-new-classes/orange_tree.rb +++ b/ch13-creating-new-classes/orange_tree.rb @@ -5,7 +5,64 @@ # 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. - class OrangeTree - # your code here + + GROWTH = 0.4 + FRUITING_AGE = 5 + MAX_AGE = 25 + + def initialize + @height = 0 + @orange_count = 0 + @age = 0 + @dead = false + end + + def dead? + @dead + end + + def height + if !dead? + @height.round(1) + else + 'A dead tree is not very tall. :(' + end + end + + def count_the_oranges + if !dead? + @orange_count.to_int + else + 'A dead tree has no oranges. :(' + end + end + + def pick_an_orange + if dead? + 'A dead tree has nothing to pick. :(' + elsif count_the_oranges >= 1 + @orange_count -= 1 + "Delicious!" + else + "No oranges on the tree :(" + end + end + + def one_year_passes + @age += 1 + + if !dead? && (@age > MAX_AGE) + @dead = true + "Oh, no! The tree is too old, and has died. :(" + elsif dead? + "A year later, the tree is still dead. :(" + else + @height += GROWTH + if @age > FRUITING_AGE + @orange_count = @height * 15 - 25 + end + "This year your tree grew to #{height}m tall, and produced #{count_the_oranges} oranges." + end + end end From 3b22f012e83cd3350aadddba83fd06b9bcb7ac29 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Mon, 12 Sep 2016 10:29:01 +0100 Subject: [PATCH 21/24] Chapter 14. Even better profiling --- ch14-blocks-and-procs/even_better_profiling.rb | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/ch14-blocks-and-procs/even_better_profiling.rb b/ch14-blocks-and-procs/even_better_profiling.rb index b01b78fd8..18f1f60fc 100644 --- a/ch14-blocks-and-procs/even_better_profiling.rb +++ b/ch14-blocks-and-procs/even_better_profiling.rb @@ -1,3 +1,11 @@ def profile block_description, &block - # your code here -end \ No newline at end of file + 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 From 8b5b3222f7e4fdfc4f6cd430f761a4c45ce8ae67 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Mon, 12 Sep 2016 10:39:30 +0100 Subject: [PATCH 22/24] Chapter 14. Grandpa clock --- ch14-blocks-and-procs/grandfather_clock.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ch14-blocks-and-procs/grandfather_clock.rb b/ch14-blocks-and-procs/grandfather_clock.rb index 916f6d354..e2774ae7c 100644 --- a/ch14-blocks-and-procs/grandfather_clock.rb +++ b/ch14-blocks-and-procs/grandfather_clock.rb @@ -1,3 +1,3 @@ def grandfather_clock &block - # your code here + Time.new.hour.times { block.call } end \ No newline at end of file From 56cd5b65477ff8dea0e85122f51ede4358b688d3 Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Mon, 12 Sep 2016 10:46:10 +0100 Subject: [PATCH 23/24] Chapter 14. Program logger --- ch14-blocks-and-procs/program_logger.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ch14-blocks-and-procs/program_logger.rb b/ch14-blocks-and-procs/program_logger.rb index 0e2e18d57..3fb888817 100644 --- a/ch14-blocks-and-procs/program_logger.rb +++ b/ch14-blocks-and-procs/program_logger.rb @@ -1,3 +1,5 @@ -def log desc, &block - # your code here +def program_log desc, &block + puts "Beginning \"#{desc}\"..." + result = block.call + puts "...\"#{desc}\" finished, returning: #{result}" end \ No newline at end of file From 654f1b6a68e967da1f8de376e3c3b2eccf45bdbf Mon Sep 17 00:00:00 2001 From: Tadas Majeris Date: Mon, 12 Sep 2016 11:03:01 +0100 Subject: [PATCH 24/24] Chapter 14. Better program loggerrr --- ch14-blocks-and-procs/better_program_logger.rb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/ch14-blocks-and-procs/better_program_logger.rb b/ch14-blocks-and-procs/better_program_logger.rb index 0e2e18d57..fe0a53691 100644 --- a/ch14-blocks-and-procs/better_program_logger.rb +++ b/ch14-blocks-and-procs/better_program_logger.rb @@ -1,3 +1,9 @@ -def log desc, &block - # your code here +$nesting_depth = 0 + +def better_log desc, &block + puts ' ' * $nesting_depth + "Beginning \"#{desc}\"..." + $nesting_depth += 1 + result = block.call + $nesting_depth -= 1 + puts ' ' * $nesting_depth + "...\"#{desc}\" finished, returning: #{result}" end \ No newline at end of file