Skip to content

Commit

Permalink
hw2 works
Browse files Browse the repository at this point in the history
  • Loading branch information
mgrishko committed Mar 9, 2012
1 parent d08cff0 commit 25d3496
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 11 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.swp
22 changes: 16 additions & 6 deletions homework2/part1.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
11 changes: 6 additions & 5 deletions homework2/part2.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -27,7 +28,7 @@ def each

private

def cartesian arrays
def cartesian(arrays)
case arrays.length
when 0
[]
Expand All @@ -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

0 comments on commit 25d3496

Please sign in to comment.