Skip to content

Instantly share code, notes, and snippets.

@jaredcwhite
Last active January 7, 2021 01:51
Show Gist options
  • Save jaredcwhite/9a2a578cc53239e31b057b27e2bc6d0e to your computer and use it in GitHub Desktop.
Save jaredcwhite/9a2a578cc53239e31b057b27e2bc6d0e to your computer and use it in GitHub Desktop.
Import keyword argument values into instance variables
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