Skip to content

Instantly share code, notes, and snippets.

@maxplomer
Last active August 29, 2015 14:04
Show Gist options
  • Save maxplomer/85f3d426663be63b237c to your computer and use it in GitHub Desktop.
Save maxplomer/85f3d426663be63b237c to your computer and use it in GitHub Desktop.
App academy learn_ruby homework solutions
#############################
#hello.rb
def hello
"Hello!"
end
def greet name
"Hello, " + name + "!"
end
#############################
#temperature.rb
def ftoc tempf
(tempf - 32.0) * 20 / (68 - 32)
end
def ctof tempc
tempc / 20.0 * (68 - 32) + 32
end
#############################
#calculator.rb
def add a, b
a+b
end
def subtract a, b
a-b
end
def sum array
array.inject(0) { |result, element| result + element }
end
def multiply *array
array.inject(:*)
end
def power a, b
a**b
end
def factorial x
return 1 if x == 0
x * factorial(x-1)
end
#############################
#simon_says.rb
def echo string
string
end
def shout string
string.upcase
end
def repeat string, times=2
((string + ' ') * times).strip
end
def start_of_word word, index
word[0..(index-1)]
end
def first_word string
string.split[0]
end
def titleize string
little_words = %w{the over and}
string.capitalize!
string.gsub(/\w+(\Z|\s)/){ |word| little_words.include?(word.strip) ? word : word.capitalize }
end
#############################
#pig_latin.rb
def translate string
string = string.split
result = []
string.each {|word| result << translate_one_word(word)}
result.join(' ')
end
def translate_one_word word
vowels = %w{a e i o u}
puncs = %w{! ? . }
punc = ''
punc = word.slice!(-1) if puncs.include?(word[-1])
return word + 'ay' + punc if vowels.include?(word[0].downcase)
beginning = ''
word_capped = word[0].between?('A','Z')
word.downcase!
while true
break if vowels.include?(word[0]) && !(beginning[-1]=='q' && word[0] == 'u') ## 'qu' exception
beginning << word.slice!(0)
end
word << beginning + 'ay' + punc
word_capped ? word.capitalize : word
end
#############################
#silly_blocks.rb
def reverser
yield.gsub!(/\w+/) {|word| word.reverse}
end
def adder(add = 1)
yield + add
end
def repeater(number_of = 1)
number_of.times {yield}
end
#############################
#performance_monitor.rb
def measure(number_of = 1)
time_start = Time.now
number_of.times {yield}
(Time.now - time_start)/number_of
end
#############################
#friend.rb
class Friend
def greeting(who = '')
who.empty? ? "Hello!" : "Hello, " + who + "!"
end
end
#############################
#book.rb
class Book
def title
@name
end
def title=(name)
little_words = %w{the a an and in of}
name.capitalize!
@name = name.gsub(/\w+(\Z|\s)/) {|word| little_words.include?(word.strip) ? word : word.capitalize}
end
end
#############################
#timer.rb
class Timer
def initialize
@seconds = 0
end
def seconds
@seconds
end
def seconds=(seconds)
@seconds = seconds
end
def time_string
sec = @seconds
hour = sec / 3600
sec -= hour * 3600
min = sec / 60
sec -= min * 60
hour.to_s.rjust(2, "0") + ":" + min.to_s.rjust(2, "0") + ":" +
sec.to_s.rjust(2, "0")
end
end
#############################
#temperature.rb
class Temperature
def initialize(options = {})
if options.include?(:f)
@temp = options[:f]
end
if options.include?(:c)
@temp = Temperature.ctof(options[:c])
end
end
def self.ftoc tempf
(tempf - 32.0) * 20 / (68 - 32)
end
def self.ctof tempc
tempc / 20.0 * (68 - 32) + 32
end
def self.from_celsius(temp)
Temperature.new(:c => temp)
end
def self.from_fahrenheit(temp)
Temperature.new(:f => temp)
end
def in_celsius
Temperature.ftoc(@temp)
end
def in_fahrenheit
@temp
end
end
class Celsius < Temperature
def initialize(temp)
@temp = Celsius.ctof(temp)
end
end
class Fahrenheit < Temperature
def initialize(temp)
@temp = temp
end
end
#############################
#dictionary.rb
class Dictionary
def initialize
@entries = {}
end
def entries
@entries
end
def add(entry)
if entry.is_a?(Hash)
@entries[entry.keys[0]] = entry.values[0]
else
@entries[entry] = nil
end
end
def keywords
@entries.keys.sort
end
def include?(entry)
@entries.include?(entry)
end
def find(entry)
result = {}
@entries.keys.each { |key| result[key]=@entries[key] if key[0..(entry.length-1)] == entry }
result
end
def printable
result = ''
keywords.each {|key| result << '[' + key + '] "' + @entries[key] + '"'+ "\n" }
result[0..-2]
end
end
#############################
#rpn_calculator.rb
class RPNCalculator
def initialize
@expr = []
@value = nil
end
def push(value)
@expr << value
end
def plus
raise "calculator is empty" if @expr.length < 2
@value = @expr.pop + @expr.pop
@expr << @value
end
def minus
raise "calculator is empty" if @expr.length < 2
@value = - @expr.pop + @expr.pop
@expr << @value
end
def divide
raise "calculator is empty" if @expr.length < 2
@value = 1.0 / @expr.pop * @expr.pop
@expr << @value
end
def times
raise "calculator is empty" if @expr.length < 2
@value = @expr.pop * @expr.pop
@expr << @value
end
def value
@value
end
def tokens(string)
operators = %w{+ - / *}
string.split.collect { |token| operators.include?(token) ? token.to_sym : token.to_i }
end
def evaluate(string)
array = tokens(string)
symbols = [:+,:-,:*,:/]
new_array = []
array.each do |x|
if symbols.include?(x)
b, a = new_array.pop, new_array.pop
new_array << symbol_math(x, a, b)
else
new_array << x
end
end
new_array[0]
end
def symbol_math symbol, a, b
return a+b if symbol == :+
return a-b if symbol == :-
return a*b if symbol == :*
return a.to_f/b if symbol == :/
end
end
#############################
#xml_document.rb
class XmlDocument
def initialize(indent = false)
@indent = indent
@depth = 0
end
def hello (hash = {})
if block_given? && @indent
@depth += 2
local_depth = @depth
return "<hello>\n" + " "*local_depth + yield + " "*(local_depth-2) + "</hello>\n"
end
return "<hello>" + yield + "</hello>" if block_given?
hash.empty? ? "<hello/>" : "<hello name='" + hash[:name] + "'/>"
end
def send(tag_name)
"<" + tag_name + "/>"
end
def goodbye (hash = {})
if block_given? && @indent
@depth += 2
local_depth = @depth
return "<goodbye>\n" + " "*local_depth + yield + " "*(local_depth-2) + "</goodbye>\n"
end
return "<goodbye>" + yield + "</goodbye>" if block_given?
"<goodbye/>"
end
def ok_fine (hash = {})
return "<ok_fine>\n" + yield + "</ok_fine>\n" if block_given? && @indent
return "<ok_fine>" + yield + "</ok_fine>" if block_given?
if @indent
hash.empty? ? "<ok_fine/>" : "<ok_fine be='" + hash[:be] + "'/>\n"
else
hash.empty? ? "<ok_fine/>" : "<ok_fine be='" + hash[:be] + "'/>"
end
end
def come_back
if block_given? && @indent
@depth += 2
local_depth = @depth
return "<come_back>\n" + " "*local_depth + yield + " "*(local_depth-2) + "</come_back>\n"
end
return "<come_back>" + yield + "</come_back>" if block_given?
"<come_back/>"
end
end
#############################
#array_extensions.rb
class Array
def sum
self.empty? ? 0 : self.inject(:+)
end
def square
self.collect {|x| x * x}
end
def square!
self.replace self.square
end
end
#############################
#in_words.rb
class Fixnum
def in_words
num_string = '' # This is the string we will return.
large_numbers = [['Sextillion', 10**21],
['Quintillion', 10**18],
['Quadrillion', 10**15],
['trillion', 10**12],
['billion', 10**9 ],
['million', 10**6 ],
['thousand', 10**3 ]]
left = self
return 'zero' if left ==0
large_numbers.each do |large_number|
write = left / large_number[1]
left = left - write * large_number[1]
if write > 0
amount_large = numbers_under_1000 write
num_string << amount_large + ' ' + large_number[0]
num_string << ' ' if left > 0
end
end
num_string << numbers_under_1000(left)
end
def numbers_under_1000 number
num_string = '' # This is the string we will return.
ones_place = %w{one two three four five six seven eight nine}
tens_place = %w{ten twenty thirty forty fifty sixty seventy eighty ninety}
teenagers = %w{eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen}
left = number
write = left / 100
left -= write * 100
if write > 0
num_string << ones_place[write - 1] + ' ' + 'hundred'
num_string << ' ' if left > 0
end
if 11 <= left && left <= 19
return num_string << teenagers[left - 11]
end
write = left / 10
left -= write * 10
if write > 0
num_string << tens_place[write - 1]
num_string << ' ' if left > 0
end
if left > 0
num_string << ones_place[left - 1]
end
num_string
end
end
@TNHuang
Copy link

TNHuang commented Jul 31, 2014

hey, Max, i think for the xml document assignment: you are suppose to dynamically generate tag. Instead of hard code each tag from the rspec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment