Created
June 14, 2012 18:28
-
-
Save pwightman/2931993 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# (a) | |
class Class | |
def attr_accessor_with_history attr | |
attr = attr.to_s | |
attr_reader attr | |
class_eval %Q{ | |
# Create a history method for the attribute | |
def #{attr}_history | |
# This isn't super elegant, but the homework examples show | |
# the arrays starting with nil. See part3.rb for an explanation | |
# of ||= | |
@#{attr}_arr ||= [nil] | |
end | |
# Sets the new value and also adds it to the array | |
# of values for that attribute | |
def #{attr}= newValue | |
@#{attr} = newValue | |
@#{attr}_arr ||= [nil] | |
@#{attr}_arr << newValue | |
end | |
} | |
end | |
end | |
class MyClass | |
attr_accessor_with_history :foo | |
attr_accessor_with_history :bar | |
end | |
#foo = MyClass.new | |
#foo.foo = "hello" | |
#foo.foo = "world" | |
#foo.foo = ["another", "thing"] | |
#puts foo.foo.inspect | |
#puts foo.foo_history.inspect | |
#foo = MyClass.new | |
#foo.bar = "that" | |
#foo.bar = "that" | |
#foo.bar = ["this", "thing"] | |
#puts foo.bar.inspect | |
#puts foo.bar_history.inspect | |
class Numeric | |
@@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1.0} | |
def method_missing(method_id) | |
singular_currency = method_id.to_s.gsub( /s$/, '') | |
if @@currencies.has_key?(singular_currency) | |
self * @@currencies[singular_currency] | |
else | |
super | |
end | |
end | |
def in curr | |
curr = curr.to_s | |
singular_currency = curr.to_s.gsub( /s$/, '') | |
self / @@currencies[curr] if @@currencies.has_key?(curr) | |
end | |
end | |
# NOTE: I don't think I'm doing this quite right, because 1.rupee.in(:rupees) should just | |
# return 0.019, but it returns 0.019*0.019. So my solution doesn't really work I don't think. | |
#puts 1.rupees.in(:rupees) | |
# (b) | |
class String | |
def palindrome? | |
str = self.downcase | |
str.gsub! /[\W]/, "" | |
str == str.reverse | |
end | |
end | |
#puts "hello".palindrome? | |
#puts "lol".palindrome? | |
# (c) | |
module Enumerable | |
def palindrome? | |
# reverse another method that's part of Enumerable, so we let it | |
# do all the work | |
arr = self.to_a | |
arr == arr.reverse | |
end | |
end | |
puts [1, 0].palindrome? | |
puts [1, 1].palindrome? | |
puts [1,2,3,2,1].palindrome? | |
puts ({ :this => "foo" }.palindrome?) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment