Cha*_*ell 84 ruby string-interpolation
在Ruby中使用字符串插值的正确方法如下:
name = "Ned Stark"
puts "Hello there, #{name}" #=> "Hello there, Ned Stark"
Run Code Online (Sandbox Code Playgroud)
这就是我打算一直使用它的方式.
但是,我注意到Ruby的字符串插值有些奇怪.我注意到字符串插值在Ruby中没有关于实例变量的花括号.例如:
@name = "Ned Stark"
puts "Hello there, #@name" #=> "Hello there, Ned Stark"
Run Code Online (Sandbox Code Playgroud)
尝试与非实例变量相同的东西不起作用.
name = "Ned Stark"
puts "Hello, there, #name" #=> "Hello there, #name"
Run Code Online (Sandbox Code Playgroud)
我在1.9.2和1.8.7中都尝试过这一点.
为什么这样做?口译员在这做什么?
tsh*_*rif 98
根据Flanagan和Matsumoto 的Ruby编程语言:
当要插入到字符串文字中的表达式只是对全局,实例或类变量的引用时,可以省略花括号.
所以以下都应该有效:
@var = "Hi"
puts "#@var there!" #=> "Hi there!"
@@var = "Hi"
puts "#@@var there!" #=> "Hi there!"
$var = "Hi"
puts "#$var there!" #=> "Hi there!"
Run Code Online (Sandbox Code Playgroud)