Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear all variables in rails console

can any body tell me what command is used to clear all variables in rails console?

e.g.

1.9.1 :001 > permissions = {:show => true}
 => {:show=>true} 
1.9.1 :001 > foo = "bar"
 => "bar"

I need a command that can get all variables reset to nil without a restart of rails console itself.

Any advice would be very much appreciated.

like image 588
Sarun Sermsuwan Avatar asked Nov 24 '12 11:11

Sarun Sermsuwan


1 Answers

local_variables.each { |e| eval("#{e} = nil") }

local_variables returns the list of symbols of all local variables in the current scope

a, b = 5, 10
local_variables # => [:b, :a]

Using each you can iterate over this list an use eval to assign their values to nil.

You can also do the same thing with instance_variables and global_variables. For example

(local_variables + instance_variables).each { |e| eval("#{e} = nil") }

By the way, if you are going to use it more than once, it might be helpful to define such method in ~/.irbrc file to make it accessible for all irb sessions (didn't test it in rails console).

class Binding
  def clear
    eval %q{ local_variables.each { |e| eval("#{e} = nil") } }
  end
end

Then, inside irb session

a = 5
binding.clear
a # => nil
like image 139
hs- Avatar answered Oct 12 '22 10:10

hs-