如何引用另一个 Ruby 代码文件中的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8116079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reference a method in another Ruby code file?
提问by Bryan
I have a Ruby code file (somelogic.rb) that contains several methods and classes, located in say, /home/user/code. Now I'm writing another class in the same directory and would like to reference to the methods and classes in somelogic.rb. How do I do that? I greatly appreciate any input.
我有一个 Ruby 代码文件 (somelogic.rb),其中包含多个方法和类,位于 /home/user/code 中。现在我正在同一目录中编写另一个类,并希望引用 somelogic.rb 中的方法和类。我怎么做?我非常感谢任何输入。
回答by David Grayson
If you are using Ruby 1.9 or later, this is the simplest way to do it:
如果您使用的是 Ruby 1.9 或更高版本,这是最简单的方法:
require_relative 'somelogic'
If you want your code to work in 1.9 and older versions of Ruby, you should do this instead:
如果您希望您的代码在 1.9 及更早版本的 Ruby 中工作,您应该这样做:
require File.join File.dirname(__FILE__), 'somelogic'
Whichever line you choose, you should put it at the top of your ruby file. Then any classes, modules, or global variables defined in somelogic.rb will be available to your program.
无论您选择哪一行,都应将其放在 ruby 文件的顶部。然后在 somelogic.rb 中定义的任何类、模块或全局变量将可用于您的程序。
回答by mliebelt
Here is the scenario:
这是场景:
/home/user/code/somelogic.rb
class MyMath
def self.sin(number)
...
end
end
You want to use the methods sinin your other file mylogic.rb.
您想使用sin其他文件中的方法mylogic.rb。
Depending on the version of ruby, do one the following:
根据 ruby 的版本,执行以下操作之一:
Ruby 1.8.x
require "somelogic"
class OtherThings
def some_method
MyMath.sin(42)
end
end
The use pattern is for all ruby versions the same, but the require statement may be different.
所有 ruby 版本的使用模式都相同,但 require 语句可能不同。
Ruby 1.9.x
require_relative "somelogic"
or variation
或变异
Ruby 1.9.x
require "./somelogic"
The first variation works all the time, the second one only if you call ruby mylogic.rbin the directory where mylogic.rband somelogic.rbare located.
第一个变体一直有效,第二个变体仅当您调用ruby mylogic.rbwheremylogic.rb和somelogic.rbare 所在的目录时。
If you want to load files from that directory from a starting point located in another directory, you should use:
如果要从位于另一个目录中的起点加载该目录中的文件,则应使用:
Ruby 1.8.x and Ruby 1.9.x
$: << File.dirname(__FILE__)
This expands the load path of Ruby. It reads the (relative) path of __FILE__, gets its directory, and adds the (absolute) path of that directory to your load path. So when doing then the lookup by require, the files will be found.
这扩展了 Ruby 的加载路径。它读取 的(相对)路径__FILE__,获取其目录,并将该目录的(绝对)路径添加到您的加载路径中。因此,在进行查找时require,将找到文件。
回答by Doug R
Check out Ruby's require keyword
回答by Bhushan Lodha
In second file (say otherlogic.rb) write require '/home/user/code/somelogic.rb' on first line.
在第二个文件(比如 otherlogic.rb)中,在第一行写 require '/home/user/code/somelogic.rb'。

