Skip to content

Instantly share code, notes, and snippets.

@DanielShuey
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save DanielShuey/a4eb0f5f9ebd0e4de90e to your computer and use it in GitHub Desktop.

Select an option

Save DanielShuey/a4eb0f5f9ebd0e4de90e to your computer and use it in GitHub Desktop.
### 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
@johncarney
Copy link

Instead of:

%w(divided_by times plus minus).zip(%w(/ * + -)).each do |o|

You can do:

%w(divided_by times plus minus).zip(%w(/ * + -)).each do |name, operator|

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment