the book中有一个例子:
"Seconds/day: #{24*60*60}" # => Seconds/day: 86400
"#{'Ho! '*3}Merry Christmas!" # => Ho! Ho! Ho! Merry Christmas!
"This is line #$." # => This is line 3
但是当我尝试在一个单独的文件中实现第三行的符号 #$
时,它会打印出 smth strange。这是我的文件 str2.rb
:
puts "Hello, World #$."
puts "Hello, World #$"
puts "#$"
现在我运行它(在 Win XP 控制台中):
C:\ruby\sbox>ruby str2.rb Hello, World 0 Hello, World ["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"] puts
I've found that #$.
(the period is mandatory) shows the line number only in Interactive Ruby Console. Used in file it produces 0
on any line. But why all that text is printed if I use symbols like this "#$" \n "#$"
?
Also such a code in a file:
puts "Hello, World #$" ## without period at the end
产生这样的错误:
C:\ruby\sbox>ruby str2.rb
str2.rb:3: unterminated string meets end of file
#$
是什么意思?在哪里以及如何使用它?
最佳答案
"#$."
是"#{$.}"
的简写,或者是全局变量的插值。类似地,#@
用于实例变量,#@@
用于类变量。
你所拥有的问题是 "#$"
中的第二个 "
不被解释为字符串的结束引号,而是作为被插值的全局变量名称的一部分 ($"
)。为了更清楚地说明您的代码实际上是如何被解释的,我将使用字符串文字代替 Ruby 认为的字符串定界符:
puts %(Hello, World #$.)
puts %(Hello, World #$"
puts )#$"
如您所见,这是输出数组的来源(它是 $"
的内容)以及末尾的“puts”字符串。#$"代码末尾的
被解释为注释。 (请注意,第二个字符串跨越并包括第二行和第三行之间的换行符。)
如果你真的想把 #$
打印成字符串,你必须转义它的一部分或使用单引号字符串:
"\#$"#=> "#$"
"#\$"#=> "#$"
'#$' #=> "#$"
简单地将 #$
放在一个内插字符串中而不进行转义是无效的,正如使用字符串文字所见:
%(#$) #=> #<SyntaxError: (eval):2: syntax error, unexpected $undefined
# %(#$)
# ^>
关于ruby - 符号序列 "#$"在 Ruby 中意味着什么以及在哪里使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15176130/