问题描述
在 Ruby 中使用字符串插值的正确方法如下:
The proper way to use string interpolation in Ruby is as follows:
name = "Ned Stark"
puts "Hello there, #{name}" #=> "Hello there, Ned Stark"
这就是我打算一直使用它的方式.
That is the way I intend to always use it.
但是,我注意到 Ruby 的字符串插值中有一些奇怪的.我注意到字符串插值在 Ruby 中可以工作,而没有关于实例变量的花括号.例如:
However, I've noticed something odd in Ruby's string interpolation. I've noticed that string interpolation works in Ruby without the curly braces in regards to instance variables. For example:
@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"
我在 1.9.2 和 1.8.7 中都成功地尝试过.
I've tried this with success in both 1.9.2 and 1.8.7.
为什么会这样?口译员在这里做什么?
Why does this work? What is the interpreter doing here?
推荐答案
根据 Flanagan 和 Matsumoto 的The Ruby Programming Language:
According to The Ruby Programming Language by Flanagan and Matsumoto:
如果要插入字符串文字的表达式只是对全局、实例或类变量的引用,则可以省略大括号.
所以以下应该都有效:
@var = "Hi"
puts "#@var there!" #=> "Hi there!"
@@var = "Hi"
puts "#@@var there!" #=> "Hi there!"
$var = "Hi"
puts "#$var there!" #=> "Hi there!"
这篇关于当没有花括号时,为什么字符串插值在 Ruby 中有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!