diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1377554 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.swp diff --git a/homework2/part1.rb b/homework2/part1.rb index 85a2098..e84755f 100644 --- a/homework2/part1.rb +++ b/homework2/part1.rb @@ -23,7 +23,7 @@ # metaprogramming to the rescue! class Numeric - @@currencies = {'dollar' => 1, 'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019} + @@currencies = { 'dollar' => 1, 'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019 } def method_missing(name) convert(name, true) or super end @@ -33,12 +33,22 @@ def in(name) end def convert(name, direct) - if direct - operation = :* - else - operation = :/ - end + operation = direct ? :* : :/ singular_currency = name.to_s.gsub( /s$/, '') @@currencies.has_key?(singular_currency) && send(operation, @@currencies[singular_currency]) end end + +class String + def palindrome? + backstring = downcase.gsub /\W/, '' + backstring == backstring.reverse + end +end + +module Enumerable + def palindrome? + pair = self.inject([[],[]]) { |acc, el| [acc.first + [el], [el] + acc.last] } + pair.first == pair.last + end +end diff --git a/homework2/part2.rb b/homework2/part2.rb index dfa332f..32f2f88 100644 --- a/homework2/part2.rb +++ b/homework2/part2.rb @@ -15,10 +15,11 @@ #Cartesian product b×a.) #To start you off, here is a code skeleton and some examples showing possible correct results. - class CartesianProduct + include Enumerable + def initialize(*args) - @product = cartesian args + @product = cartesian(args) end def each @@ -27,7 +28,7 @@ def each private - def cartesian arrays + def cartesian(arrays) case arrays.length when 0 [] @@ -40,8 +41,8 @@ def cartesian arrays end end - def trivial_cartesian arrays + def trivial_cartesian(arrays) lhs, rhs = *arrays - lhs.inject([]) { |acc, i| acc + ([i] * rhs.length).zip(rhs)} + lhs.inject([]) { |acc, i| acc + ([i] * rhs.length).zip(rhs) } end end