Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby 'script = $0'

Tags:

ruby

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 "? "
STDIN.gets

puts "Opening the file..."
target = File.open(filename, 'w')

puts "Truncating the file. Goodbye!"
target.truncate(target.size)

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."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

puts "And finally, we close it."
target.close()
like image 353
user1152142 Avatar asked Apr 28 '12 15:04

user1152142


People also ask

What is $0 Ruby?

$0 is the name of the file used to start the program. This check says “If this is the main file being used…” This allows a file to be used as a library, and not to execute code in that context, but if the file is being used as an executable, then execute that code.

What is __ file __ in Ruby?

__FILE__ is the name of the current file. The script bellow test if the current file is the one we use on the command line, with : ruby script.rb if __FILE__ == $0 puts "we are running this file (it's not included somewhere)" end.


2 Answers

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

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

like image 112
KL-7 Avatar answered Oct 06 '22 03:10

KL-7


Oh the classic Zed Shaw books! lol The $0 gets the input on the command line before the first argument. So say you were to run this through the command line using the ruby interpreter you could put "ruby (fileName) test.txt" and $0 will pick up the fileName and save it to the variable 'script'. I'm not really sure why your doing it here because you do use it later in the program, but that's it. The way you could have tested this would be to print it on the screen using puts, perhaps add this bit of code to see it yourself somewhere in the code:

puts "The $0 has saved #{script} to it, I wonder where it got that."

and see it will name your file.

like image 38
Chance Freeze Avatar answered Oct 06 '22 03:10

Chance Freeze