2

书中有一个例子:

"Seconds/day: #{24*60*60}" # => Seconds/day: 86400
"#{'Ho! '*3}Merry Christmas!" # => Ho! Ho! Ho! Merry Christmas!
"This is line #$." # => This is line 3

但是当我尝试#$在一个单独的文件中实现第三行的符号时,它会打印出奇怪的东西。这是我的文件str2.rb

puts "Hello, World #$."
puts "Hello, World #$"
puts "#$"

现在我运行它(在 Win XP 控制台中):

C:\ruby\sbox>ruby str2.rb
你好,世界 0
你好,世界 ["enumerator.so", "C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/i386-mingw32/enc/encdb.so", "C:/Rai
lsInstaller/Ruby1.9.3/lib/ruby/1.9.1/i386-mingw32/enc/windows_1251.so", "C:/RailsInstaller/Ruby1.9.3/lib/ruby/
1.9.1/i386-mingw32/enc/trans/transdb.so", "C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/defau
lts.rb", "C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/i386-mingw32/rbconfig.rb", "C:/RailsInstaller/Ruby1.9.3/l
ib/ruby/site_ruby/1.9.1/rubygems/deprecate.rb", "C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems
/exceptions.rb", "C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/defaults/operating_system.rb",
 "C:/RailsInstaller/Ruby1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb", "C:/RailsInstaller/Ruby1.9
.3/lib/ruby/site_ruby/1.9.1/rubygems.rb", "C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/i386-mingw32/enc/utf_16l
e.so”、“C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/i386-mingw32/enc/trans/utf_16_32.so”、“C:/RailsInstaller/Ru
by1.9.3/lib/ruby/1.9.1/i386-mingw32/enc/trans/single_byte.so"]
看跌期权

我发现#$.(该句点是强制性的)仅在交互式 Ruby 控制台中显示行号。用于它0在任何行上生成的文件。但是,如果我使用这样的符号,为什么会打印所有这些文本"#$" \n "#$"

文件中还有这样的代码:

puts "Hello, World #$" ## without period at the end

产生这样的错误:

C:\ruby\sbox>ruby str2.rb
str2.rb:3: unterminated string meets end of file

是什么#$意思?在哪里以及如何使用它?

4

2 回答 2

6

"#$."是 的简写"#{$.}",或者是全局变量的插值。同样,#@对于实例变量和#@@类变量也是如此。

你所拥有的问题是第二个"in没有"#$"被解释为字符串的结束引号,而是作为被插值的全局变量名的一部分()。为了更清楚您的代码实际上是如何被解释的,我将使用字符串文字代替 Ruby 认为的字符串分隔符:$"

puts %(Hello, World #$.)
puts %(Hello, World #$"
puts )#$"

如您所见,这是打印的数组的来源(它是 的内容$")以及末尾的“puts”字符串。#$"代码末尾的 被解释为注释。(请注意,第二个字符串跨越并包括第二行和第三行之间的换行符。)

如果您确实想打印#$为字符串,则必须转义其中的一部分或使用单引号字符串:

  • "\#$" #=> "#$"
  • "#\$" #=> "#$"
  • '#$' #=> "#$"

简单地放入#$一个没有转义的插值字符串是无效的,这可以通过使用字符串文字看出:

%(#$)  #=> #<SyntaxError: (eval):2: syntax error, unexpected $undefined
       #   %(#$)
       #      ^>
于 2013-03-02T15:47:04.673 回答
0

在 Ruby 中,全局变量是使用美元符号定义的。

$foo = "bar"

有一些预定义的全局变量,例如

# last line number seen by interpreter
$.

我想你只是错过了这个时期。您可以使用 - 将变量插入到字符串中

"line #{$.}"

或速记

"line #$."
于 2013-03-02T15:55:14.187 回答