在Ruby中,我怎麼能檢測未使用/未分配的表情和做一些與他們這樣的:紅寶石:檢測未使用/未分配的表情
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
現在我想實例化一個東西,沒有它明確地分配給一個變量,而是在實例化時自動分配一個變量:
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
是你的單身之後? –
絕對不是。 – themirror