字符串[16]在17个字符的字符串上失败?

Luc*_*ips 3 ruby

specialChars = "]%#$!_.+?~&[*/^;@"

puts(specialChars[16])
Run Code Online (Sandbox Code Playgroud)

打印一个空行.为什么会这样?我需要逃避一些角色吗?

Aar*_*nin 6

# 是用">分隔时用于字符串插值的保留字符:

# Example
puts "My name is #{my_name}!"
Run Code Online (Sandbox Code Playgroud)

如果使用''而不是"",则禁用字符串插值,您可以正常使用它:

# The "" has been replaced with ''
specialChars = ']%#$!_.+?~&[*/^;@'
puts specialChars[16]
# => '@'
Run Code Online (Sandbox Code Playgroud)

  • @LucasPhillips如果后跟一个看起来可能是变量名的一部分的字符,它仍然会使用插值.例如`"#@ foo"`会使用`@ foo`的值.在你的情况下,它使用系统变量`$!`的内容 (5认同)