如何引用另一个 Ruby 代码文件中的方法? [英] How to reference a method in another Ruby code file?

查看:41
本文介绍了如何引用另一个 Ruby 代码文件中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Ruby 代码文件 (somelogic.rb),其中包含多个方法和类,例如位于/home/user/code.现在我正在同一目录中编写另一个类,并希望引用 somelogic.rb 中的方法和类.我怎么做?我非常感谢任何输入.

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 1.9 或更高版本,这是最简单的方法:

If you are using Ruby 1.9 or later, this is the simplest way to do it:

require_relative 'somelogic'

如果您希望您的代码在 1.9 及更早版本的 Ruby 中工作,您应该这样做:

If you want your code to work in 1.9 and older versions of Ruby, you should do this instead:

require File.join File.dirname(__FILE__), 'somelogic'

无论选择哪一行,都应将其放在 ruby​​ 文件的顶部.然后在 somelogic.rb 中定义的任何类、模块或全局变量都将可用于您的程序.

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 代码文件中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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