user1152142 user1152142 - 1 year ago 90
Ruby Question

Ruby 'script = $0'

I was looking at a Ruby script and I came across

script = $0
. I have done some Googling but I have not found a definite answer as to what this does. I believe that it protects you from reading a file bigger than memory, is that correct?

Thanks, I have the full script below so you can see it in context:

# Takes the name of a file as an argument and assigns to filename
filename = ARGV.first
script = $0

puts "We're going to erase #{filename}."
puts "If you don't want that, hit CTRL-C (^C)."
puts "If you do want that, hit RETURN."

print "? "

puts "Opening the file..."
target =, 'w')

puts "Truncating the file. Goodbye!"

puts "Now I'm going to ask you for three lines."

print "line 1: "; line1 = STDIN.gets.chomp()
print "line 2: "; line2 = STDIN.gets.chomp()
print "line 3: "; line3 = STDIN.gets.chomp()

puts "I'm going to write these to the file."


puts "And finally, we close it."

Answer Source

$0 is one of Ruby's global variables. From here:

$0 -- Contains the name of the script being executed. May be assignable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download