Skip to content

Instantly share code, notes, and snippets.

@kudosqujo
Last active April 9, 2020 00:34
Show Gist options
  • Select an option

  • Save kudosqujo/6c76a5de86083878b4dc511708718528 to your computer and use it in GitHub Desktop.

Select an option

Save kudosqujo/6c76a5de86083878b4dc511708718528 to your computer and use it in GitHub Desktop.
[instance_eval and Procs] Using instance_eval and code blocks
# 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
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