在Ruby中,获取当前文件路径可以通过多种方式实现,以下是一些常用的方法:
__FILE__
:File.expand_path
:Dir.pwd
:__FILE__
获取当前脚本的绝对路径。File.expand_path
时,确保基准路径设置正确。以下是一个综合示例,展示了如何在不同情况下获取当前文件路径:
# 获取当前脚本文件的绝对路径
current_file_path = __FILE__
puts "Current file path: #{current_file_path}"
# 将相对路径转换为绝对路径
base_directory = "/home/user/projects"
relative_script = "scripts/example.rb"
absolute_script_path = File.expand_path(relative_script, base_directory)
puts "Absolute script path: #{absolute_script_path}"
# 获取当前工作目录的路径
current_directory = Dir.pwd
puts "Current directory: #{current_directory}"
通过上述方法,可以灵活且准确地获取Ruby中的当前文件路径,满足不同场景下的需求。
领取专属 10元无门槛券
手把手带您无忧上云