“$”是什么意思? Ruby 中的字符是什么意思?
使用 Ruby on Rails 有一段时间了,决定查看一下实际的源代码。从 GitHub 上获取存储库并开始四处寻找。遇到一些代码,我不确定它的作用或引用的内容。
我在 actionmailer/test/abstract_unit.rb 中看到了这段代码
root = File.expand_path('../../..', __FILE__)
begin
require "#{root}/vendor/gems/environment"
rescue LoadError
$:.unshift("#{root}/activesupport/lib")
$:.unshift("#{root}/actionpack/lib")
end
lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
require 'rubygems'
require 'test/unit'
require 'action_mailer'
require 'action_mailer/test_case'
有人能告诉我 $: (又名“the bling”)引用了什么吗?
Been playing with Ruby on Rails for awhile and decided to take a look through the actual source. Grabbed the repo from GitHub and started looking around. Came across some code that I am not sure what it does or what it references.
I saw this code in actionmailer/test/abstract_unit.rb
root = File.expand_path('../../..', __FILE__)
begin
require "#{root}/vendor/gems/environment"
rescue LoadError
$:.unshift("#{root}/activesupport/lib")
$:.unshift("#{root}/actionpack/lib")
end
lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
require 'rubygems'
require 'test/unit'
require 'action_mailer'
require 'action_mailer/test_case'
Can someone tell me what the $: (a.k.a. "the bling") is referencing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
$
标识全局变量,而不是局部变量、@instance 变量或@@class 变量。语言提供的全局变量有
$:
,它也由$LOAD_PATH
标识$
identifies a global variable, as opposed to a local variable, @instance variable, or @@class variable.Among the language-supplied global variables are
$:
, which is also identified by$LOAD_PATH
$:
是用于查找外部文件的全局变量。来自 https://docs.ruby-lang.org/en/3.2/globals_rdoc .html
$:
is the global variable used for looking up external files.From https://docs.ruby-lang.org/en/3.2/globals_rdoc.html
我想指出一些关于 Ruby 的奇怪的事情!
$
确实意味着加载路径。;
表示“结束行”。但!$;
表示字段分隔符。尝试在 REPL 中运行$;.to_s
,您将看到它返回","
。这还不是全部!$
带有其他后缀可以表示还有很多其他的事情。为什么? 好吧,当然是 Perl!
I wanna note something weird about Ruby!
$
does indeed mean load path. And;
means "end line". But!$;
means field separator. Try running$;.to_s
in your REPL and you'll see it return","
. That's not all!$
with other suffixes can mean many other things.Why? Well, Perl of course!
引用 Ruby 论坛:
ruby 附带了一组预定义的变量,
如果我明白的话正确(不是 100% 确定)这会将 lib 路径添加到该数组
通过遍历当前文件来确定搜索路径。这不完全是
最好的方法,我会简单地从 RAILS_ROOT 开始(至少对于 Rails
项目)
To quote the Ruby Forum:
ruby comes with a set of predefined variables
if i get it right (not 100% sure) this adds the lib path to this array
of search paths by going over the current file. which is not exactly the
best way, i would simply start with RAILS_ROOT (at least for a rails
project)
与 相同
。您也可以说:
它们是设置加载路径的非常常见的 Ruby 习惯用法。
is the same as
. You can also say:
They are pretty common Ruby idioms to set a load path.