for gem i'm working on need add variable main, preferably local variable, instance works well. i've been trying use object.instance_variable_set
, have made no progress way. how can accomplish this?
clarification
i need set instance variable module within main
.
here situation:
module mygem::submodule def self.add_variable_to_main object.instance_variable_set(:@var,"value") end def self.recieve_variable_from_main object.instance_variable_get(:@var) end def self.store_block @@block=&block end def self.call_block add_variable_to_main @@block.call puts recieve_variable_from_main end end class object include mygem::submodule end store_block @var = "var #{@var}" end call_block
i asked this question same problem, has additional details.
main
object, objects can't have local variables. local variables belong lexical scopes, not objects.
you can assign instance variable in context of main
:
@ivar = 42
now main
has instance variable @ivar
value of 42
.
object#instance_variable_set
works same way:
instance_variable_set(:@ivar, 42)
if not within context of main
, can access top-level binding
via global constant toplevel_binding
, , main
object via toplevel_binding.receiver
, since main
implicit receiver, i.e. self
@ top-level:
module foo toplevel_binding.receiver.instance_variable_set(:@ivar, 42) end @ivar # => 42
Comments
Post a Comment