Last active
January 7, 2021 01:51
-
-
Save jaredcwhite/9a2a578cc53239e31b057b27e2bc6d0e to your computer and use it in GitHub Desktop.
Import keyword argument values into instance variables
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
def set_ivars_from_keys(local_binding, *keys) | |
keys.each do |key| | |
instance_variable_set :"@#{key}", local_binding.local_variable_get(key) | |
end | |
end | |
def test(a:, b:) | |
set_ivars_from_keys binding, :a | |
end | |
test(a: 1, b: 2) | |
@a # 1 | |
@b # 2 | |
#### | |
def set_ivars_automatically(local_binding) | |
local_binding.local_variables.each do |key| | |
instance_variable_set :"@#{key}", local_binding.local_variable_get(key) | |
end | |
end | |
def test2(a:, b:) | |
set_ivars_automatically binding | |
end | |
test2(a: 1, b: 2) | |
@a # 1 | |
@b # 2 | |
#### | |
def set_ivars_from_block_binding(&block) | |
local_binding = block.binding | |
local_binding.local_variables.each do |key| | |
instance_variable_set :"@#{key}", local_binding.local_variable_get(key) | |
end | |
end | |
def test3(a:, b:) | |
set_ivars_from_block_binding {} | |
end | |
test3(a: 1, b: 2) | |
@a # 1 | |
@b # 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment