Undefine variable in Ruby

后端 未结 5 1256
迷失自我
迷失自我 2020-12-05 06:29

Let\'s say I\'m using irb, and type a = 5. How do I remove the definition of a so that typing a returns a NameError

5条回答
  •  Happy的楠姐
    2020-12-05 06:50

    In the spirit of the question, you could limit the variable to a scope, assuming you are okay with other local variables being locked to the same scope. This is useful particularly if you are defining something in a class and don't want the local variable to stay around in the class declaration.

    The only ways I can think to do this is with Integer#times or Array#each like so:

    1.times do |a|
      a = 5
      # code…
    end
    
    [5].each do |a|
      # code…
    end
    

    There are probably other, even cleaner ways to limit to a block besides this. These aren't as clean as I'd like and I'd love to see if someone has a cleaner method to use to do this.

提交回复
热议问题