Ruby 脚本可以告诉它在哪个目录中吗? [英] Can a Ruby script tell what directory it’s in?

查看:17
本文介绍了Ruby 脚本可以告诉它在哪个目录中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

灵感来自获取源目录"中的 Bash 脚本,Ruby 的方法是什么?

Inspired by "Getting the source directory of a Bash script from within", what's the Ruby way to do this?

推荐答案

对于较新版本的 Ruby,请尝试:

For newer versions of Ruby, try:

  • __dir__

对于旧版本的 Ruby (<2.0),可以使用以下命令找到正在运行的脚本:

For older versions of Ruby (< 2.0), the script being run can be found using:

  • File.dirname(__FILE__) - 相对路径;或
  • File.expand_path(File.dirname(__FILE__)) - 绝对路径.
  • File.dirname(__FILE__) - relative path; or
  • File.expand_path(File.dirname(__FILE__)) - the absolute path.

注意:即使在调用 Dir.chdir 之后,使用 __dir__ 也会返回脚本路径;而使用旧语法可能不会返回脚本的路径.

Note: Using __dir__ will return the script path even after a call to Dir.chdir; whereas, using the older syntax may not return the path to the script.

这篇关于Ruby 脚本可以告诉它在哪个目录中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆