diff --git a/ask_method.rb b/ask_method.rb new file mode 100644 index 000000000..840846492 --- /dev/null +++ b/ask_method.rb @@ -0,0 +1,26 @@ +def ask question + 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 welcome to pointless questions." + +ask "Do you like cake?" +ask "Do you like birthdays?" +ask "Do you like the idea of going to bed right now for a solid 8 hours sleep??" + +# tidy up method by removing the answer variable. +# use return to exit from the loop \ No newline at end of file diff --git a/ch09-writing-your-own-methods/ask.rb b/ch09-writing-your-own-methods/ask.rb index 01716eb35..aabeea853 100644 --- a/ch09-writing-your-own-methods/ask.rb +++ b/ch09-writing-your-own-methods/ask.rb @@ -1,3 +1,17 @@ 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 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..cdd7451d0 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,39 @@ def old_roman_numeral num - # your code here -end \ No newline at end of file + while num.to_i <= 3000 + array = num.to_s.split(//).map { |x| x.to_i } + result =[] + until array.length == 4 + array.unshift(0) + end + if array[-4] < 5 + number = array[-4] + number.times { result << "M" } + end + if array[-3] < 5 + number = array[-3] + number.times { result << "C" } + else + number = array[-3] + result << "D" + (number-5).times { result << "C" } + end + if array[-2] < 5 + number = array[-2] + number.times { result << "X" } + else + number = array[-2] + result << "L" + (number-5).times { result << "X" } + end + if array[-1] < 5 + number = array[-1] + number.times { result << "I" } + else + number = array[-1] + result << "V" + (number-5).times { result << "I" } + end + return result.join("") + end + return "Number must be greater than 3000." +end diff --git a/ch09-writing-your-own-methods/roman_numerals.rb b/ch09-writing-your-own-methods/roman_numerals.rb index 5c93b59ac..fb6fae4d0 100644 --- a/ch09-writing-your-own-methods/roman_numerals.rb +++ b/ch09-writing-your-own-methods/roman_numerals.rb @@ -1,3 +1,74 @@ def roman_numeral num - # your code here -end \ No newline at end of file + while num.to_i <= 3000 + # split number into an array + array = num.to_s.split(//).map { |x| x.to_i } + result =[] + # array has length of 4 + until array.length == 4 + array.unshift(0) + end + # 1000s of number + if array[-4] < 4 + number = array[-4] + number.times { result << "M" } + end + # 100s of number + if array[-3] < 4 + number = array[-3] + number.times { result << "C" } + elsif array[-3] == 4 + number = array[-3] + result << "CD" + elsif array[-3] == 6 + number = array[-3] + result << "DC" + elsif array[-3] == 9 + number = array[-3] + result << "CM" + else + number = array[-3] + result << "D" + (number-5).times { result << "C" } + end + # 10s of number + if array[-2] < 4 + number = array[-2] + number.times { result << "X" } + elsif array[-2] == 4 + number = array[-2] + result << "XL" + elsif array[-2] == 6 + number = array[-2] + result << "LX" + elsif array[-2] == 9 + number = array[-2] + result << "XC" + else + number = array[-2] + result << "L" + (number-5).times { result << "X" } + end + # single digits of number + if array[-1] < 4 + number = array[-1] + number.times { result << "I" } + elsif array[-1] == 4 + number = array[-1] + result << "IV" + elsif array[-1] == 6 + number = array[-1] + result << "VI" + elsif array[-1] == 9 + number = array[-1] + result << "IX" + else + number = array[-1] + result << "V" + (number-5).times { result << "I" } + end + # return number in roman numerals + return result.join("") + end + puts "Number must be greater than 3000." + exit +end diff --git a/ch10-nothing-new/dictionary_sort.rb b/ch10-nothing-new/dictionary_sort.rb index c9893d0fd..8ac735230 100644 --- a/ch10-nothing-new/dictionary_sort.rb +++ b/ch10-nothing-new/dictionary_sort.rb @@ -1,3 +1,39 @@ def dictionary_sort arr - # your code here -end \ No newline at end of file + recursive_sort(arr, []) +end + +def recursive_sort unsorted_array, sorted_array + if unsorted_array.length < 1 + return sorted_array + end + + smallest = unsorted_array.pop + still_unsorted = [] + + unsorted_array.each { |tested_object| + if tested_object.downcase < smallest.downcase + still_unsorted << smallest + smallest = tested_object + else + still_unsorted << tested_object + end + } + sorted_array << smallest + recursive_sort still_unsorted, sorted_array +end +puts dictionary_sort(['Apple', 'apple', 'Banana', 'BANANA', 'banana']).join(' ') +# print sort(['apple', 'Apple', 'APPLE']) + +# put everything to downcase, sort, then revert back to original. + +# smallest = APPLE 65 +# tested_object = apple 97 +# 65 < 97 therefore tested_object < smallest FALSE, still_unsorted << apple +# tested_object = Apple 65 +# 65 < 97 therefore tested_object< smallest FALSE, still_unsorted << Apple +# tested_object = APPLE 86 +# 97 < 97 FALSE, still unsorted << APPLE + +# print dictionary_sort(['testing', 'with', 'DUPLICATE', 'duplicate', 'words', 'alright']) +# print dictionary_sort(['f', 'v', 'e', 'd', 'j', 'f']) +# print dictionary_sort(['Apple', 'apple', 'Banana', 'BANANA', 'banana']) \ No newline at end of file diff --git a/ch10-nothing-new/english_number.rb b/ch10-nothing-new/english_number.rb index c0129bc4e..ab38ab1d8 100644 --- a/ch10-nothing-new/english_number.rb +++ b/ch10-nothing-new/english_number.rb @@ -1,3 +1,88 @@ def english_number number - # your code here + + if number < 0 + return "Please enter a number that isn't negative." + end + if number == 0 + return 'zero' + end + + num_string = '' + ones_place = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] + tens_place = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] + teenagers = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] + zillions = [ + ['hundred', 2], ['thousand', 3], ['million', 6], ['billion', 9], ['trillion', 12], ['quadrillion', 15], + ['quintillion', 18], ['sextillion', 21], ['septillion', 24], ['octillion', 27], ['nonillion', 30], + ['decillion', 33], ['undecillion', 36], ['duodecillion', 39], ['tredecillion', 42], ['quattuordecillion', 45], + ['quindecillion', 48], ['sexdecillion', 51], ['septendecillion', 54], ['octodecillion', 57], ['novemdecillion', 60], + ['vigintillion', 63], ['googol', 100] + ] + + left = number + + # Zillions + while zillions.length > 0 + zil_pair = zillions.pop + zil_name = zil_pair[0] + zil_base = 10 ** zil_pair[1] + write = left/zil_base + left = left - write*zil_base + + if write > 0 + prefix = english_number write + num_string = num_string + prefix + ' ' + zil_name + if left > 0 + num_string = num_string + ' ' + end + end + end + + # Tens + write = left/10 + left = left - write*10 + + if write > 0 + if ((write == 1) and (left > 0)) + num_string = num_string + teenagers[left-1] + left = 0 + else + num_string = num_string + tens_place[write-1] + end + + if left > 0 + num_string = num_string + '-' + end + end + + # Single digits + write = left + left = 0 + + if write > 0 + num_string = num_string + ones_place[write - 1] + end + + 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(101) +puts english_number(234) +puts english_number(3211) +puts english_number(999999) +puts english_number(574645) +puts english_number(1000000) +puts english_number(1000000000000) +puts english_number(1000000000032) +puts english_number(2343234355434457357) +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..0d5c1bf09 100644 --- a/ch10-nothing-new/ninety_nine_bottles_of_beer.rb +++ b/ch10-nothing-new/ninety_nine_bottles_of_beer.rb @@ -1 +1,98 @@ -# your code here \ No newline at end of file +def english_number number + + if number < 0 + return "Please enter a number that isn't negative." + end + if number == 0 + return 'zero' + end + + num_string = '' + ones_place = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] + tens_place = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] + teenagers = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] + zillions = [ + ['hundred', 2], ['thousand', 3], ['million', 6], ['billion', 9], ['trillion', 12], ['quadrillion', 15], + ['quintillion', 18], ['sextillion', 21], ['septillion', 24], ['octillion', 27], ['nonillion', 30], + ['decillion', 33], ['undecillion', 36], ['duodecillion', 39], ['tredecillion', 42], ['quattuordecillion', 45], + ['quindecillion', 48], ['sexdecillion', 51], ['septendecillion', 54], ['octodecillion', 57], ['novemdecillion', 60], + ['vigintillion', 63], ['googol', 100] + ] + + left = number + + # Zillions + while zillions.length > 0 + zil_pair = zillions.pop + zil_name = zil_pair[0] + zil_base = 10 ** zil_pair[1] + write = left/zil_base + left = left - write*zil_base + + if write > 0 + prefix = english_number write + num_string = num_string + prefix + ' ' + zil_name + if left > 0 + num_string = num_string + ' ' + end + end + end + + # Tens + write = left/10 + left = left - write*10 + + if write > 0 + if ((write == 1) and (left > 0)) + num_string = num_string + teenagers[left-1] + left = 0 + else + num_string = num_string + tens_place[write-1] + end + if left > 0 + num_string = num_string + '-' + end + end + + # Single digits + 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 english_number(num_now) + " bottles of beer on the wall, " + puts english_number(num_now) + " bottles of beer. " + puts "Take one down and what have you got... " + num_now = num_now - 1 + puts 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!" + +# 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(101) +# puts english_number(234) +# puts english_number(3211) +# puts english_number(999999) +# puts english_number(574645) +# puts english_number(1000000) +# puts english_number(1000000000000) +# puts english_number(1000000000032) +# puts english_number(2343234355434457357) +# puts english_number(109238745102938560129834709285360238475982374561034) diff --git a/ch10-nothing-new/shuffle.rb b/ch10-nothing-new/shuffle.rb index a486ad94c..24fa817bf 100644 --- a/ch10-nothing-new/shuffle.rb +++ b/ch10-nothing-new/shuffle.rb @@ -1,3 +1,14 @@ def shuffle arr - # your code here -end \ No newline at end of file + recursive_shuffle arr, [] +end + +def recursive_shuffle old_array, new_array + until old_array.length < 1 + new_array << old_array.delete_at(rand(old_array.length)) + end + new_array +end + +shuffle([1, 4, 5, 10, 2, 2]) +shuffle(['testing', 'with', 'words']) +shuffle(['a', 'b', 'c', 'd', 'e', 'f', 'g']) \ No newline at end of file diff --git a/ch10-nothing-new/sort.rb b/ch10-nothing-new/sort.rb index 44c6deb58..3ccea87ad 100644 --- a/ch10-nothing-new/sort.rb +++ b/ch10-nothing-new/sort.rb @@ -1,3 +1,30 @@ def sort arr - # your code here -end \ No newline at end of file + recursive_sort(arr, []) +end + +def recursive_sort unsorted_array, sorted_array + if unsorted_array.length < 1 + return sorted_array + end + + smallest = unsorted_array.pop + still_unsorted = [] + + unsorted_array.each { |tested_object| + if tested_object < smallest + still_unsorted << smallest + smallest = tested_object + else + still_unsorted << tested_object + end + } + sorted_array << smallest + recursive_sort still_unsorted, sorted_array +end + + +print sort(['testing', 'with', 'duplicate', 'duplicate', 'words', 'alright']) +print sort(['testing', 'with', 'DUPLICATE', 'duplicate', 'words', 'alright']) + +print sort(['f', 'v', 'e', 'd', 'j', 'f']) +print sort(['Apple', 'apple', 'Banana', 'BANANA', 'banana']) \ No newline at end of file diff --git a/ch11-reading-and-writing/build_a_better_playlist.rb b/ch11-reading-and-writing/build_a_better_playlist.rb index 3b31bd241..214db1867 100644 --- a/ch11-reading-and-writing/build_a_better_playlist.rb +++ b/ch11-reading-and-writing/build_a_better_playlist.rb @@ -1,3 +1,32 @@ def music_shuffle filenames - # your code here + mp3_sort = filenames.sort + mp3_length = filenames.length + + # shuffle twice + 2.times do + left_pile_index = 0 + right_pile_index = mp3_length/2 + shuffle = [] + while shuffle.length < mp3_length + if shuffle.length%2 == 0 + # take care from right pile + shuffle.push(mp3_sort[right_pile_index]) + right_pile_index = right_pile_index + 1 + else + # take care from left pile + shuffle.push(mp3_sort[left_pile_index]) + left_pile_index = left_pile_index + 1 + end + end + mp3_sort = shuffle + end + # cut the deck + array = [] + cut_deck = rand(mp3_length) #index of card to cut at + index = 0 + while index < mp3_length + array.push(mp3_sort[(index+cut_deck)%mp3_length]) + index = index + 1 + end + array 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..d94a5d355 100644 --- a/ch11-reading-and-writing/build_your_own_playlist.rb +++ b/ch11-reading-and-writing/build_your_own_playlist.rb @@ -1 +1,22 @@ -# your code here \ No newline at end of file +def shuffle arr + recursive_shuffle arr, [] +end + +def recursive_shuffle old_array, new_array + until old_array.length < 1 + new_array << old_array.delete_at(rand(old_array.length)) + end + new_array +end + +# build playlist + # search for mp3 files at specified address + # using shuffle method to mix it up +mp3_files = shuffle(Dir['/Users/jen/Music/Albums/**/*.{MP3,mp3}']) + +# write mp3 files to playlist.m3u +playlist = 'playlist.m3u' +File.open playlist, 'w' do |f| + f.write mp3_files +end + diff --git a/ch11-reading-and-writing/safer_picture_downloading.rb b/ch11-reading-and-writing/safer_picture_downloading.rb index 801de24bd..404948a58 100644 --- a/ch11-reading-and-writing/safer_picture_downloading.rb +++ b/ch11-reading-and-writing/safer_picture_downloading.rb @@ -1 +1,43 @@ -# your code here \ No newline at end of file +# shows pwd +Dir.pwd +# change directory to where you want files to be saved +Dir.chdir '/Users/Jen/someDir/pictures/' + +# find all the pictures to be moved to the current directory +file_names = Dir['/Users/jen/Makers-Academy/pre-course/week2/ruby_files/**/*.jpg'] + +# give the batch of files a name +puts "What would you like to call this batch?" +batch_name = gets.chomp + +# download pictures to pwd +print "Downloading #{file_names.length} files: " +# This is the counter +file_number = 1 +file_names.each { |name| + # does file already exist? + # file renaming + # iterate over all found files and rename + print '.' #this is the progress bar + new_name = if file_number < 10 + "#{batch_name}0#{file_number}.jpg" + else + "#{batch_name}#{file_number}.jpg" + end + if File.exists?(new_name) + puts "This file already exists. Do you want to overwrite this file?" + answer = gets.chomp + if answer == "yes" + File.rename(name, new_name) + else + puts "Not moving this file." + end + else + File.rename(name, new_name) + end + # increment counter + file_number = file_number + 1 +} + +puts +puts "Done!" \ No newline at end of file diff --git a/ch12-new-classes-of-objects/birthday_helper.rb b/ch12-new-classes-of-objects/birthday_helper.rb index 801de24bd..31b63aa8d 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 +require 'date' +require 'time_difference' + +current_date = Time.now +puts current_date + +birth_dates = {} + +# write a program to read in names and birth dates from a text file +File.readlines('birthdays.txt').each do |line| + name, date, year = line.split(',') + birth_dates[name] = Time.gm(year, *(date.split)) #gives birth time in year-month-date-hour-minute-second format +end + +# ask for a name +puts "Please type the name you require: " +name = gets.chomp +puts + +# getting dates in the format we would like +bday = birth_dates[name].strftime("%e of %B, %Y.") +bday_month = birth_dates[name].strftime("%B") +bday_date = birth_dates[name].strftime("%e") + +age_in_years = TimeDifference.between(bday, current_date).in_years.to_i + +# output +puts "#{name} will be #{age_in_years+1} on #{bday_date} of #{bday_month}.#{}" diff --git a/ch12-new-classes-of-objects/birthdays.txt b/ch12-new-classes-of-objects/birthdays.txt new file mode 100644 index 000000000..ea3492642 --- /dev/null +++ b/ch12-new-classes-of-objects/birthdays.txt @@ -0,0 +1,8 @@ +Christopher Alexander, Oct 4, 1936 +Christopher Lambert, Mar 29, 1957 +Christopher Lee, May 27, 1922 +Christopher Lloyd, Oct 22, 1938 +Christopher Pine, Aug 3, 1976 +Christopher Plummer, Dec 13, 1927 +Christopher Walken, Mar 31, 1943 +The King of Spain, Jan 5, 1938 diff --git a/ch12-new-classes-of-objects/happy_birthday.rb b/ch12-new-classes-of-objects/happy_birthday.rb index 801de24bd..2dad72a60 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 +require 'date' +require 'time_difference' + +# Today's date +current_date = Time.new +# ask what year a person was born +puts "What year were you born?" +year = gets.chomp +# then the month +puts "What month were you born?" +month = gets.chomp +# then the day +puts "What date were you born?" +date = gets.chomp + +# figure out how old they are +age = Time.mktime(year, month, date) +diff_in_years = TimeDifference.between(age, current_date).in_years.to_i +# give them a big SPANK for each birthday they have had. +puts "Here are #{diff_in_years} spanks for your birthday!" +diff_in_years.times do |spank| + print "SPANK! " +end \ No newline at end of file diff --git a/ch12-new-classes-of-objects/one_billion_seconds.rb b/ch12-new-classes-of-objects/one_billion_seconds.rb index 801de24bd..ae84a2244 100644 --- a/ch12-new-classes-of-objects/one_billion_seconds.rb +++ b/ch12-new-classes-of-objects/one_billion_seconds.rb @@ -1 +1,16 @@ -# your code here \ No newline at end of file +require 'date' +# find the exact second you were born. + +# set starting time to 0 - epoch +starting_time = Time.at(0) +puts starting_time +# set finishing time to my birthday +birthday = Time.mktime(1982, 12, 6, 22, 0) +puts birthday +# find difference +seconds = birthday - starting_time +puts "I was born #{seconds} seconds after the epoch." + +# find out when you will turn 1 billion seconds old. +one_billion_secs = birthday + 1000000000 +puts "By #{one_billion_secs}, I will be 1 billion seconds old." \ No newline at end of file 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..765576b68 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,35 @@ -def roman_to_integer roman - # your code here -end \ No newline at end of file +def roman_to_integer(roman) + digit_values = { + '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_values[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("CXX") diff --git a/ch13-creating-new-classes/extend_built_in_classes.rb b/ch13-creating-new-classes/extend_built_in_classes.rb index c3e793933..6dff81215 100644 --- a/ch13-creating-new-classes/extend_built_in_classes.rb +++ b/ch13-creating-new-classes/extend_built_in_classes.rb @@ -1,3 +1,95 @@ class Integer - # your code here -end \ No newline at end of file + def factorial + if self < 0 + return "You can't take the factorial out of a negative number!" + end + if self <= 1 + 1 + else + self * (self-1).factorial + end + end + + def to_roman + while self.to_i <= 3000 + # split number into an array + array = self.to_s.split(//).map { |x| x.to_i } + result =[] + # array has length of 4 + until array.length == 4 + array.unshift(0) + end + # 1000s of number + if array[-4] < 4 + number = array[-4] + number.times { result << "M" } + end + # 100s of number + if array[-3] < 4 + number = array[-3] + number.times { result << "C" } + elsif array[-3] == 4 + number = array[-3] + result << "CD" + elsif array[-3] == 6 + number = array[-3] + result << "DC" + elsif array[-3] == 9 + number = array[-3] + result << "CM" + else + number = array[-3] + result << "D" + (number-5).times { result << "C" } + end + # 10s of number + if array[-2] < 4 + number = array[-2] + number.times { result << "X" } + elsif array[-2] == 4 + number = array[-2] + result << "XL" + elsif array[-2] == 6 + number = array[-2] + result << "LX" + elsif array[-2] == 9 + number = array[-2] + result << "XC" + else + number = array[-2] + result << "L" + (number-5).times { result << "X" } + end + # single digits of number + if array[-1] <= 4 + number = array[-1] + number.times { result << "I" } + # elsif array[-1] == 4 + # number = array[-1] + # result << "IV" + elsif array[-1] == 6 + number = array[-1] + result << "VI" + # elsif array[-1] == 9 + # number = array[-1] + # result << "IX" + else + number = array[-1] + result << "V" + (number-5).times { result << "I" } + end + # return number in roman numerals + return result.join("") + end + puts "Number must be greater than 3000." + exit + end +end + + +# puts 59.to_roman +# puts 1323.roman_numeral +# puts 1999.roman_numeral + +# puts 3.factorial +# puts 10.factorial diff --git a/ch13-creating-new-classes/factorial_extended.rb b/ch13-creating-new-classes/factorial_extended.rb new file mode 100644 index 000000000..54ba24971 --- /dev/null +++ b/ch13-creating-new-classes/factorial_extended.rb @@ -0,0 +1,15 @@ +class Integer + def factorial + if self < 0 + return "You can't take the factorial out of a negative number!" + end + if self <= 1 + 1 + else + self * (self-1).factorial + end + end +end + +puts 3.factorial +puts 10.factorial \ No newline at end of file diff --git a/ch13-creating-new-classes/interactive_baby_dragon.rb b/ch13-creating-new-classes/interactive_baby_dragon.rb index 801de24bd..a8a8699b1 100644 --- a/ch13-creating-new-classes/interactive_baby_dragon.rb +++ b/ch13-creating-new-classes/interactive_baby_dragon.rb @@ -1 +1,113 @@ -# your code here \ No newline at end of file +class Dragon + def initialize name + @name = name + @asleep = false + @stuff_in_belly = 10 #full + @stuff_in_intestine = 0 # doesn't need toilet + + 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 slow." + 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 doses off..." + passage_of_time + if @asleep + @asleep = false + puts "...but wakes up 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 #dragon is starving! + 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} does the potty dance..." + end + end +end + +require_relative 'dragon.rb' + +# ask what you want to name the dragon +puts "What do you want to call your new pet dragon?" +name = gets.chomp +pet = Dragon.new name + +while true + # ask what you want to do to the dragon? + puts "What shall we do with #{name}?" + answer = gets.chomp.downcase + +# if walk, feed, toss, put to bed, rock, call those methods. + if answer == "walk" + pet.walk + elsif answer == "feed" + pet.feed + elsif answer == "put to bed" + pet.put_to_bed + elsif answer == "rock" + pet.rock + elsif answer == "toss" + pet.toss + else + puts "I don't understand this activity! Please try again." + # stuff + end +end \ No newline at end of file diff --git a/ch13-creating-new-classes/orange_tree.rb b/ch13-creating-new-classes/orange_tree.rb index 025d08907..06b07c81b 100644 --- a/ch13-creating-new-classes/orange_tree.rb +++ b/ch13-creating-new-classes/orange_tree.rb @@ -1,11 +1,100 @@ -# in order to pass the rspec please follow the below rates of growth, orange production and age of death. -# have your OrangeTree grow by 0.4 per year. -# have it produce no oranges in its first 5 years -# starting in its sixth year have it produce oranges at a rate of (height * 15 - 25) per year. -# have the tree die after 25 years. -# check out the rspec spec/ch13/orange_tree_spec.rb to see what strings we're looking for in the responses. - - class OrangeTree - # your code here + + def initialize + @height = 0 + @orange_count = 0 + @alive = true + # puts "Your orange tree has started to grow." + end + def height + # height method returns height + if @alive + @height.round(1) + # "Your tree is #{@height} metres tall." + else + "A dead tree is not very tall. :(" + end + end + def count_the_oranges + # count_the_oranges method returns number of oranges on the tree + if @alive + @orange_count + # puts "There are #{@orange_count} oranges on the tree." + else + "A dead tree has no oranges. :(" + end + end + def one_year_passes + if @alive + @height = (@height + 0.4).round(2) + @orange_count = 0 + if @height > 10 + # tree dies + @alive = false + "Oh, no! The tree is too old, and has died. :(" + elsif @height > 2 + # new oranges grow + # Older trees produce more each year than younger trees. + @orange_count = (@height * 15 - 25).to_i + "This year your tree grew to #{@height}m tall, and produced #{@orange_count} oranges." + else + "This year your tree grew to #{@height}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 + "That orange was so delicious!" + else + "There are no oranges left." + end + else + "A dead tree has nothing to pick. :(" + end + end end + + +ot = OrangeTree.new +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes +ot.one_year_passes + + +puts ot.one_year_passes +# tree.one_year_passes +# tree.one_year_passes +# # tree.orange_count +# # tree.pick_an_orange +# # tree.pick_an_orange +# tree.height +# tree.one_year_passes + +# tree.one_year_passes diff --git a/ch13-creating-new-classes/roman_numerals_extended.rb b/ch13-creating-new-classes/roman_numerals_extended.rb new file mode 100644 index 000000000..042520838 --- /dev/null +++ b/ch13-creating-new-classes/roman_numerals_extended.rb @@ -0,0 +1,81 @@ +class Integer + + def roman_numeral + while self.to_i <= 3000 + # split number into an array + array = self.to_s.split(//).map { |x| x.to_i } + result =[] + # array has length of 4 + until array.length == 4 + array.unshift(0) + end + # 1000s of number + if array[-4] < 4 + number = array[-4] + number.times { result << "M" } + end + # 100s of number + if array[-3] < 4 + number = array[-3] + number.times { result << "C" } + elsif array[-3] == 4 + number = array[-3] + result << "CD" + elsif array[-3] == 6 + number = array[-3] + result << "DC" + elsif array[-3] == 9 + number = array[-3] + result << "CM" + else + number = array[-3] + result << "D" + (number-5).times { result << "C" } + end + # 10s of number + if array[-2] < 4 + number = array[-2] + number.times { result << "X" } + elsif array[-2] == 4 + number = array[-2] + result << "XL" + elsif array[-2] == 6 + number = array[-2] + result << "LX" + elsif array[-2] == 9 + number = array[-2] + result << "XC" + else + number = array[-2] + result << "L" + (number-5).times { result << "X" } + end + # single digits of number + if array[-1] < 4 + number = array[-1] + number.times { result << "I" } + elsif array[-1] == 4 + number = array[-1] + result << "IV" + elsif array[-1] == 6 + number = array[-1] + result << "VI" + elsif array[-1] == 9 + number = array[-1] + result << "IX" + else + number = array[-1] + result << "V" + (number-5).times { result << "I" } + end + # return number in roman numerals + return result.join("") + end + puts "Number must be greater than 3000." + exit + end +end + +puts 10.roman_numeral +puts 1323.roman_numeral +puts 1999.roman_numeral \ No newline at end of file diff --git a/ch13-creating-new-classes/shuffle_extended.rb b/ch13-creating-new-classes/shuffle_extended.rb new file mode 100644 index 000000000..bd27d36aa --- /dev/null +++ b/ch13-creating-new-classes/shuffle_extended.rb @@ -0,0 +1,19 @@ +class Array + def shuffle + arr = self + recursive_shuffle arr, [] + end + + def recursive_shuffle old_array, new_array + until old_array.length < 1 + new_array << old_array.delete_at(rand(old_array.length)) + end + print new_array + end +end + +# shuffle([1, 4, 5, 10, 2, 2]) +# shuffle(['testing', 'with', 'words']) +# shuffle(['a', 'b', 'c', 'd', 'e', 'f', 'g']) + +puts [1, 4, 5, 10, 2, 2].shuffle \ No newline at end of file diff --git a/ch14-blocks-and-procs/better_program_logger.rb b/ch14-blocks-and-procs/better_program_logger.rb index 0e2e18d57..afb4dea47 100644 --- a/ch14-blocks-and-procs/better_program_logger.rb +++ b/ch14-blocks-and-procs/better_program_logger.rb @@ -1,3 +1,24 @@ -def log desc, &block - # your code here +$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 'some teeny-tiny block' do + 'lOtS oF lOve'.downcase + end + 7 * 3 * 2 + end + + better_log 'yet another block' do + '!doof iahT ekil I'.reverse + end + '0' == 0 end \ No newline at end of file diff --git a/ch14-blocks-and-procs/even_better_profiling.rb b/ch14-blocks-and-procs/even_better_profiling.rb index b01b78fd8..8a688dbdd 100644 --- a/ch14-blocks-and-procs/even_better_profiling.rb +++ b/ch14-blocks-and-procs/even_better_profiling.rb @@ -1,3 +1,22 @@ def profile block_description, &block - # your code here + start_time = Time.new + block.call + duration = Time.new - start_time + puts "#{block_description}: #{duration} seconds" +end + +profile '25000 doublings' do + number = 1 + 25000.times do + number = number + number + end + puts "#{number.to_s.length} digits" + # i.e number of digits in this huge number +end + +profile 'count to a million' do + number = 0 + 1000000.times do + number = number + 1 + end end \ No newline at end of file diff --git a/ch14-blocks-and-procs/grandfather_clock.rb b/ch14-blocks-and-procs/grandfather_clock.rb index 916f6d354..5b725ac2f 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 + # number of hours since midnight + hour = Time.new.hour + if hour > 12 + hour = hour - 12 + elsif hour == 0 + hour = 12 + else + hour + end + hour.times do + yield + 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..78aa1f0a3 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 +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 \ No newline at end of file diff --git a/test b/test new file mode 100644 index 000000000..e69de29bb