In ruby, how can I detect unused/unassigned expressions and do something with them like this:
class Thing
attr_accessor :name
def initialize(name)
@name = name
#if a new instantiation of this class is not assigned to anything
#or used by a calling method, then make a variable called #{name}
#and assign it to this new instantiation
if not assigned_or_used
global_variable_set(name, this)
end
end
def to_s
"Hi from #{name}"
end
end
Now I want to instantiate a Thing without explicitly assigning it to a variable, but rather have a variable assig开发者_运维百科ned to it automatically when it is instantiated:
bob = Thing.new("bob")
puts bob
#=> "Hi from bob"
#works ordinarily
Thing.new("fred")
puts fred
#=> "Hi from fred"
#works after implementing the code for instantiation of Thing
#without explicit assignment/use by a method
Yeesh, I don't know. I could be misunderstanding, but this sounds like a really bad idea (maybe you can provide a specific example of why you want to do this).
Questions that come to mind:
- Are you just trying to save keystrokes?
- What if there's a name conflict (you make two calls to
Thing.new("fred")
in a row) - what happens to the variable? - Do you really want to do this, and do you really want to create a global variable on top of it, stripping away all scope safety?
- If this is even possible, can you dig into the garbage collector to do this?
The garbage collector automatically (but only periodically) frees memory when no references exist to an object. Seems like if you did this (creating variables for ALL "Things" unassigned) that you'd be creating a memory leak, and going around the garbage collector's purpose in life. You'd also possibly be fighting the garbage collector - meaning, right after you create an object, if the garbage collector runs between then, and when the variable is created, you'd lose the object anyway.
精彩评论