简体   繁体   English

Ruby中的“$”字符是什么意思?

[英]What does the “$” character mean in Ruby?

Been playing with Ruby on Rails for awhile and decided to take a look through the actual source. 一直在使用Ruby on Rails并决定查看实际来源。 Grabbed the repo from GitHub and started looking around. 抓住GitHub的回购并开始环顾四周。 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 我在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 $: (aka "the bling") is referencing? 有人能告诉我$ :(又名“bling”)引用了什么?

$ identifies a global variable, as opposed to a local variable, @instance variable, or @@class variable. $标识全局变量,而不是局部变量,@ instance变量或@@类变量。

Among the language-supplied global variables are $: , which is also identified by $LOAD_PATH 语言提供的全局变量中有$: ,它也由$LOAD_PATH标识

$: is the global variable used for looking up external files. $:是用于查找外部文件的全局变量。

From http://www.zenspider.com/Languages/Ruby/QuickRef.html#18 来自http://www.zenspider.com/Languages/Ruby/QuickRef.html#18

$: Load path for scripts and binary modules by load or require. $:按加载或要求加载脚本和二进制模块的路径。

To quote the Ruby Forum: 引用Ruby论坛:

ruby comes with a set of predefined variables ruby带有一组预定义变量

$: = default search path (array of paths)
__FILE__ = current sourcefile

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. 如果我做对了(不是100%肯定),这将通过遍历当前文件将lib路径添加到此搜索路径数组。 which is not exactly the best way, i would simply start with RAILS_ROOT (at least for a rails project) 这不是最好的方式,我只想从RAILS_ROOT开始(至少对于一个rails项目)

I wanna note something weird about Ruby! 我想注意一些关于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 "," . 尝试在REPL中运行$;.to_s ,你会看到它返回"," That's not all! 那不是全部! $ with other suffixes can mean many other things . $与其他后缀可能意味着许多其他事情

Why? 为什么? Well, Perl of course! 好吧,Perl当然!

$:.unshift

is the same as 是相同的

$LOAD_PATH.unshift

. You can also say: 你也可以说:

$: <<
$LOAD_PATH <<

They are pretty common Ruby idioms to set a load path. 它们是设置加载路径的常用Ruby习语。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM