Last active
April 9, 2020 00:34
-
-
Save kudosqujo/6c76a5de86083878b4dc511708718528 to your computer and use it in GitHub Desktop.
[instance_eval and Procs] Using instance_eval and code blocks
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
| # Will experience a performance benefit over #instance_eval as | |
| # this method will experience only 1 scope change whereas with | |
| # #instance_eval, that will happen for each request | |
| def generate_method(method_name, &block) | |
| method_name = method_name.to_sym | |
| define_method(method_name, &block) | |
| # grab the unbound method block | |
| method = instance_method method_name | |
| remove_method method_name | |
| method | |
| end |
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
| a = [1,2,3,4,5] | |
| block = proc { size } | |
| a.instance_eval(&block) #=> 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment