当没有花括号时,为什么字符串插值在 Ruby 中有效?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10091156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does string interpolation work in Ruby when there are no curly braces?
提问by Charles Caldwell
The proper way to use string interpolation in Ruby is as follows:
在 Ruby 中使用字符串插值的正确方法如下:
name = "Ned Stark"
puts "Hello there, #{name}" #=> "Hello there, Ned Stark"
That is the way I intend to always use it.
这就是我打算始终使用它的方式。
However, I've noticed something oddin Ruby's string interpolation. I've noticed that string interpolation works in Ruby without the curly braces in regards to instance variables. For example:
但是,我注意到Ruby 的字符串插值有些奇怪。我注意到字符串插值在 Ruby 中可以工作,而没有关于实例变量的花括号。例如:
@name = "Ned Stark"
puts "Hello there, #@name" #=> "Hello there, Ned Stark"
And that trying the same thing as a non-instance variable does not work.
尝试与非实例变量相同的事情是行不通的。
name = "Ned Stark"
puts "Hello, there, #name" #=> "Hello there, #name"
I've tried this with success in both 1.9.2 and 1.8.7.
我已经在 1.9.2 和 1.8.7 中成功地尝试过这个。
Why does this work? What is the interpreter doing here?
为什么这样做?口译员在这里做什么?
回答by tsherif
According to The Ruby Programming Languageby Flanagan and Matsumoto:
根据Flanagan 和 Matsumoto 的The Ruby Programming Language:
When the expression to be interpolated into the string literal is simply a reference to a global, instance or class variable, then the curly braces may be omitted.
当要插入字符串文字的表达式只是对全局、实例或类变量的引用时,可以省略大括号。
So the following should all work:
所以以下应该都有效:
@var = "Hi"
puts "#@var there!" #=> "Hi there!"
@@var = "Hi"
puts "#@@var there!" #=> "Hi there!"
$var = "Hi"
puts "#$var there!" #=> "Hi there!"

