Skip to content

Instantly share code, notes, and snippets.

@chikoski
Created February 5, 2013 05:09
Show Gist options
  • Save chikoski/4712309 to your computer and use it in GitHub Desktop.
Save chikoski/4712309 to your computer and use it in GitHub Desktop.
instance_evalをつかって加算器をつくってみた。
Accumulator
attr_reader :result
def initialize
@result = 0
end
def add(a, b)
return @result += a + b
end
def sub(a, b)
return @result += a - b
end
def times(a, b)
return @result += a * b
end
def div(a, b)
return @result += a / b
end
def mod(a, b)
return @result += a % b
end
def calc(&proc)
instance_eval(&proc)
end
end
a = Accumulator.new
a.calc do
add(1, 1)
sub(0, 2)
times(4, 4)
div(4, 4)
mod(7, 3)
puts result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment