Skip to content

@Ejhfast /meta.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Fun with Metaprogramming in Ruby
class FStore
attr_accessor :dynamic_methods
def initialize
@dynamic_methods = []
end
def mix(s1, s2, s3, &block)
name = "#{s1.to_s}_#{s2.to_s}_#{s3.to_s}".to_sym
self.send(name) {|a,b| send(s1, send(s2,a), send(s3,b))}
end
def method_missing(symbol, &block)
if block_given?
self.class.send :define_method, symbol, &block
else
bdy = proc {|*x| symbol}
self.class.send :define_method, symbol, bdy
end
@dynamic_methods << symbol
symbol
end
end
e = FStore.new
# Define a bunch of methods dynamically
e.double {|x| 2*x}
e.triple {|x| 3*x}
e.square {|x| x**2}
e.plus {|x,y| x + y}
# Mix a few methods
e.mix(:plus, :double, :triple)
puts "All e's new methods:"
e.dynamic_methods.each {|x| puts "\t#{x.to_s}"}
puts "\nEval: e.plus_double_triple(2,3)"
puts e.plus_double_triple 2, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.