在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