6

我正在查看一个 Ruby 脚本,我遇到了script = $0. 我做了一些谷歌搜索,但我还没有找到一个明确的答案。我相信它可以保护您免于读取大于内存的文件,对吗?

谢谢,我有下面的完整脚本,所以你可以在上下文中看到它:

# 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()
4

2 回答 2

13

$0是 Ruby 的全局变量之一。从这里

$0 -- 包含正在执行的脚本的名称。可能是可分配的。

于 2012-04-28T15:19:27.430 回答
1

哦,经典的 Zed Shaw 书籍!大声笑 $0 在第一个参数之前获取命令行上的输入。因此,假设您要使用 ruby​​ 解释器通过命令行运行它,您可以输入“ruby (fileName) test.txt”,$0 将获取文件名并将其保存到变量“脚本”中。我不太确定你为什么在这里这样做,因为你稍后会在程序中使用它,但就是这样。您可以对此进行测试的方法是使用 puts 将其打印在屏幕上,或者添加这段代码以便您自己在代码中的某处查看它:

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

并看到它会命名你的文件。

于 2015-08-25T22:31:59.763 回答