Skip to content

Instantly share code, notes, and snippets.

@liezl200
Last active August 29, 2015 14:18
Show Gist options
  • Save liezl200/3212c98b26252ea421d0 to your computer and use it in GitHub Desktop.
Save liezl200/3212c98b26252ea421d0 to your computer and use it in GitHub Desktop.
Ruby Metaprogramming: Powers
class Power
def initialize(x)
@x = x
end
def method_missing(method, *args, &block)
if /^pow[0-9]+$/ =~ method
n = /[0-9]+/.match(method.to_s)
pw = n.to_s.to_i
eval("def " << method.to_s << "\nres = 1\n(1..#{pw}).each do |c|\nres *= @x\n end\n return res\nend\n")
eval("self." << method.to_s)
else
super.method_missing
end
end
end
a = Power.new(29)
puts a.pow3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment