Guest User

Untitled

a guest
Oct 20th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. # (a)
  2. class Class
  3. def attr_accessor_with_history attr
  4.  
  5. attr = attr.to_s
  6.  
  7. attr_reader attr
  8.  
  9. class_eval %Q{
  10. # Create a history method for the attribute
  11. def #{attr}_history
  12. # This isn't super elegant, but the homework examples show
  13. # the arrays starting with nil. See part3.rb for an explanation
  14. # of ||=
  15. @#{attr}_arr ||= [nil]
  16. end
  17.  
  18. # Sets the new value and also adds it to the array
  19. # of values for that attribute
  20. def #{attr}= newValue
  21. @#{attr} = newValue
  22. @#{attr}_arr ||= [nil]
  23. @#{attr}_arr << newValue
  24. end
  25. }
  26. end
  27.  
  28. end
  29.  
  30.  
  31. class MyClass
  32. attr_accessor_with_history :foo
  33. attr_accessor_with_history :bar
  34. end
  35.  
  36. #foo = MyClass.new
  37. #foo.foo = "hello"
  38. #foo.foo = "world"
  39. #foo.foo = ["another", "thing"]
  40. #puts foo.foo.inspect
  41. #puts foo.foo_history.inspect
  42.  
  43. #foo = MyClass.new
  44. #foo.bar = "that"
  45. #foo.bar = "that"
  46. #foo.bar = ["this", "thing"]
  47. #puts foo.bar.inspect
  48. #puts foo.bar_history.inspect
  49.  
  50.  
  51. class Numeric
  52. @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1.0}
  53. def method_missing(method_id)
  54. singular_currency = method_id.to_s.gsub( /s$/, '')
  55. if @@currencies.has_key?(singular_currency)
  56. self * @@currencies[singular_currency]
  57. else
  58. super
  59. end
  60. end
  61.  
  62. def in curr
  63. curr = curr.to_s
  64.  
  65. singular_currency = curr.to_s.gsub( /s$/, '')
  66. self / @@currencies[curr] if @@currencies.has_key?(curr)
  67. end
  68. end
  69.  
  70. # NOTE: I don't think I'm doing this quite right, because 1.rupee.in(:rupees) should just
  71. # return 0.019, but it returns 0.019*0.019. So my solution doesn't really work I don't think.
  72. #puts 1.rupees.in(:rupees)
  73.  
  74. # (b)
  75.  
  76.  
  77. class String
  78. def palindrome?
  79. str = self.downcase
  80. str.gsub! /[\W]/, ""
  81. str == str.reverse
  82. end
  83. end
  84.  
  85. #puts "hello".palindrome?
  86. #puts "lol".palindrome?
  87.  
  88. # (c)
  89.  
  90. module Enumerable
  91. def palindrome?
  92. # reverse another method that's part of Enumerable, so we let it
  93. # do all the work
  94. arr = self.to_a
  95. arr == arr.reverse
  96. end
  97. end
  98.  
  99. puts [1, 0].palindrome?
  100. puts [1, 1].palindrome?
  101. puts [1,2,3,2,1].palindrome?
  102. puts ({ :this => "foo" }.palindrome?)
Add Comment
Please, Sign In to add comment