如何获取Crystal脚本的编译版本以获得自己的__FILE__。这是一个例子。我有一个名为〜/ test.cr的文件,其中包含以下内容:
puts __FILE__
我通过Crystal
编译脚本~$ crystal ~/test.cr -o ~/test.compiled
接下来我运行〜/ test.compiled。我产生了结果
/Users/Account1/test.cr
即使__FILE__实际上是
/Users/Account1/test.compiled
有没有办法让它产生
/Users/Account1/test.compiled
而不是
/Users/Account1/test.cr
答案 0 :(得分:7)
元常量__FILE__
始终指向源文件,而不是可执行文件。但是,您可以使用$0
获取当前可执行路径(或使用File.expand_path
的完整路径):
foo.cr:
puts $0
puts File.expand_path($0)
然后编译并执行:
$~ crystal build foo.cr
$~ ./foo
./foo
/Users/MyUser/foo