加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 没有#{}的字符串插值

发布时间:2020-12-17 01:42:21 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why does string interpolation work in Ruby when there are no curly braces?????????????????????????????????????1个 请注意以下事项: "abcd#fg" # = "abcd#fg""abcd#$fg" # = "abcd" characters #$and after them are skipped"abcd#@fg"
参见英文答案 > Why does string interpolation work in Ruby when there are no curly braces?????????????????????????????????????1个
请注意以下事项:

"abcd#fg"  # => "abcd#fg"
"abcd#$fg" # => "abcd"    characters #$and after them are skipped
"abcd#@fg" # => "abcd"    characters #@ and after them are skipped

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

$fg = 8
"abcd#$fg" # => "abcd8" 
@fg = 6
"abcd#@fg" # => "abcd6"

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

解决方法

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

$world = 'world'
puts "hello,#$world"
# hello,world

在你的例子中,$fg和@fg都是未初始化的,因此被评估为nil,这就是为什么它们作为空字符串被内嵌的原因.当你写“abcd#fg”时,没有插入任何内容,因为#后面没有{,@,$.

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

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

@variable = 'foo'
puts "#@variable_bar"

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读