ruby - How can we delete an object (having an integer identifier)? -
i delete object, can not. here example:
irb(main):001:0> str = "hello" "hello" irb(main):003:0> str.object_id 2164703880 irb(main):004:0> str = nil nil irb(main):005:0> str.object_id 4
as can see, can set variable of object nil (and of course object id 4). , after that, garbage collector delete automatically unused object id: 2164703880.
but no, don't want that. want remove object.
thanks ideas, suggestions.
you cannot un-define local variable in ruby. can use remove_class_variable, remove_instance_variable , remove_const, can't local variables.
in code removing string object, or @ least garbage collector removing it. thing keep around pointer, named str, points nil. actual string object no longer exist.
one way ensure variables un-defined wrap them in proc. of course has downside of having create proc, , it's easier let ruby perform garbage collection. if want use proc, define it's own binding , can force local variables, this:
proc.new{ |;str| str = "hello"; puts str.object_id }.call 2227691880 => nil defined?(str) => nil
keep in mind ruby object oriented programing language, it's easier deal variables inside of objects rather worry globally scoped variables. if variables defined inside of functions , objects, remain local functions , objects , cease exist once objects removed.
Comments
Post a Comment