Last active
August 29, 2015 14:08
-
-
Save DanielShuey/a4eb0f5f9ebd0e4de90e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| ### Chainable Eval | |
| class Calc | |
| %w(zero one two three four five six seven eight nine divided_by times plus minus).zip((0..9).to_a + %w(/ * + -)) do |d| | |
| define_method(d.first.to_sym) { (@exp ||= []) << d.last; self } | |
| end | |
| define_method(:==) { |expected| eval(@exp.join) == expected } | |
| end | |
| ### Chainable No Eval | |
| class Fixnum | |
| %w(divided_by times plus minus).zip(%w(/ * + -)).each do |o| | |
| define_method(o.first.to_sym) { Calc.new(o.last.to_sym, self) } | |
| end | |
| end | |
| class Calc | |
| %w(zero one two three four five six seven eight nine).zip((0..9).to_a) do |operand| | |
| define_method(operand.first.to_sym) { @operation ? @total.send(@operation, operand.last) : operand.last } | |
| end | |
| def initialize operation = nil, total = nil | |
| @operation, @total = operation, total | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of:
You can do: