为什么相对路径在 Ruby 中不起作用需要 [英] Why relative path doesn't work in Ruby require

查看:58
本文介绍了为什么相对路径在 Ruby 中不起作用需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习 Ruby,有一件事我不明白,为什么 require 指令的相对路径在 ruby​​ 中不起作用.它几乎适用于我现在的所有脚本语言(JSP、PHP...).我用一个真实的例子来解释.我有一个名为 shapes 的文件夹,其中包含 3 个类 shaperectanglesquare.我还有另一个文件 test_shapes.rb ,我在那里调用和测试我的类.当我像这样将我的类导入主文件时:

I'm starting learning Ruby, one thing that I don't understand, why relative path for require directive doesn't work in ruby. It's something that works almost in every scripting language that I now (JSP, PHP...). I explain with a real example. I have a folder named shapes which contains 3 classes shape, rectangle and square. I have also another file test_shapes.rb from where I call and test my classes. When I import my classes to the main file like this:

require "./shape"
require "./rectangle"
require "./square"

我收到未找到文件的错误.当我像这样包含子文件夹的名称时:

I got error for files not found. When I include the name of my subfolder like this:

require "./shapes/shape"
require "./shapes/rectangle"
require "./shapes/square"

代码完美运行.因为我指定了项目根目录的整个路径(我认为是lib文件夹).当我包含时,我包含了硬盘的绝对路径,如下所示:

The code is perfectly working. Because I specified the whole path to the root directory of the project (the lib folder I think). When I include I include the absolute path to the hard disk, like this:

require "#{File.dirname(__FILE__)}/shape"
require "#{File.dirname(__FILE__)}/rectangle"
require "#{File.dirname(__FILE__)}/square"

它也能完美运行.

所以,如果知道为什么第一个导入方法(当前文件夹的相对路径)不起作用,我只想解释一下.

So, I just want some explanation if know why the first import method (the relative path to the current folder) in not working.

推荐答案

相对路径基于工作目录.我假设在同一目录中有主文件.如果您在项目根目录上运行 ruby ./shapes/main.rb,ruby 会尝试找到 {project_root}/shape.rb,而不是 {project_root}/shapes/shape.rb.它不起作用.

Relative path is based on working dir. I assume that there is main file on the same directory. If you run ruby ./shapes/main.rb on project root, ruby try to find {project_root}/shape.rb, not {project_root}/shapes/shape.rb. It doesn't work.

你需要像下面这样使用 require_relative.

You need to use require_relative like below.

# {project_root}/shapes/main.rb
require_relative './shape'
require_relative './rectangle'
require_relative './square'

这篇关于为什么相对路径在 Ruby 中不起作用需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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