没有#{}的字符串插值

Vir*_*ual 3 ruby

请注意以下事项:

"abcd#fg"  # => "abcd#fg"
"abcd#$fg" # => "abcd"    characters #$ and after them are skipped
"abcd#@fg" # => "abcd"    characters #@ and after them are skipped
Run Code Online (Sandbox Code Playgroud)

它可以是字符串插值#而不是#{}.

$fg = 8
"abcd#$fg" # => "abcd8" 
@fg = 6
"abcd#@fg" # => "abcd6" 
Run Code Online (Sandbox Code Playgroud)

它像插值一样工作.这是一个错误还是一个功能?

tor*_*o2k 7

您实际上可以插入省略大括号的全局,实例和类变量:

$world = 'world'
puts "hello, #$world"
# hello, world
Run Code Online (Sandbox Code Playgroud)

在您的例子都$fg@fg未初始化,因此评价nil,这就是为什么他们都intorpolated为空字符串.当你写"abcd#fg"什么,因为是插#后面没有之一{,@,$.

您可以在RubySpec中找到记录的功能(感谢@DavidMiani).

如果你问我,不要依赖这种行为,并且总是使用大括号插入变量,这既是为了便于阅读,也是为了避免出现以下问题:

@variable = 'foo'
puts "#@variable_bar"
Run Code Online (Sandbox Code Playgroud)

这将输出一个空字符串而不是可能的预期字符串"foo_bar",因为它试图插入未定义的实例变量@variable_bar.

  • 它存在于[ruby spec string string](https://github.com/rubyspec/rubyspec/blob/master/language/string_spec.rb)中,因此任何通过该规范的ruby都将使用该语法. (2认同)