Skip to content

Instantly share code, notes, and snippets.

@ievgrafov
Created March 14, 2016 09:53
Show Gist options
  • Save ievgrafov/42a0ec18565c38458603 to your computer and use it in GitHub Desktop.
Save ievgrafov/42a0ec18565c38458603 to your computer and use it in GitHub Desktop.
formula building example
class Formula
attr_accessor :value
def initialize(v)
@value = v
end
def to_s
value
end
[:=~, :+, :-].each do |operator_name|
define_method(operator_name) do |operand|
self.class.new("#{self} #{operator_name} #{operand}")
end
end
end
class FormulaInterpreter
class << self
def instance
@instance ||= new
end
end
def method_missing(method_name, *args)
super unless args.empty?
@variables ||= {}
@variables[method_name] ||= Formula.new(method_name.to_s)
end
end
def formula(&block)
FormulaInterpreter.instance.instance_eval(&block)
end
f = formula { a =~ b + c - d + b + 1 }
puts f
# => 'a =~ b + c - d + b + 1'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment