Created
October 7, 2011 16:17
-
-
Save padi/1270700 to your computer and use it in GitHub Desktop.
Improvement in defining methods.
This file contains hidden or 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 Numeric | |
| [['multiply', '*'], ['divide', '/'], ['add', '+'], ['subtract', '-']].each do |method, operator| | |
| define_method("#{method}_10") do | |
| method(operator).call(10) # line not readable, should be something like self + 10, self - 10, etc... | |
| end | |
| end | |
| end | |
| puts 40.add_10 | |
| puts 40.subtract_10 | |
| puts 40.divide_10 | |
| puts 40.multiply_10 |
This file contains hidden or 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 Numeric | |
| [['multiply', '*'], ['divide', '/'], ['add', '+'], ['subtract', '-']].each do |method, operator| | |
| module_eval %{ | |
| def #{method}_10 | |
| self.#{operator}(10) | |
| end | |
| } | |
| end | |
| end | |
| ['multiply', 'divide', 'add', 'subtract'].each { |method| eval %{ puts 40.#{method}_10 } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment