Last active
August 29, 2015 14:18
-
-
Save liezl200/3212c98b26252ea421d0 to your computer and use it in GitHub Desktop.
Ruby Metaprogramming: Powers
This file contains 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
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