为什么这在 Ruby 中可行:
"foo" "bar"
# => "foobar"
我不确定为什么字符串被连接在一起而没有出现语法错误。
我很好奇这是否是预期行为,以及解析器是否负责处理它(两个没有运算符的字符串被视为单个字符串),或者语言定义本身指定了这种行为(隐式连接)。
为什么这在 Ruby 中可行:
"foo" "bar"
# => "foobar"
我不确定为什么字符串被连接在一起而没有出现语法错误。
我很好奇这是否是预期行为,以及解析器是否负责处理它(两个没有运算符的字符串被视为单个字符串),或者语言定义本身指定了这种行为(隐式连接)。
Adjacent string literals are automatically concatenated by the interpreter:
"con" "cat" "en" "at" "ion" #=> "concatenation" "This string contains "\ "no newlines." #=> "This string contains no newlines."
Any combination of adjacent single-quote, double-quote, percent strings will be concatenated as long as a percent-string is not last.
%q{a} 'b' "c" #=> "abc" "a" 'b' %q{c} #=> NameError: uninitialized constant q
"a" %q{b} "c"
,链接会抛出 syntax error, unexpected tSTRING_BEG, expecting end-of-input
的语法错误。 - Glutexo实现细节可以在Ruby源代码的parse.y
文件中找到。具体而言,在这里。
Ruby的string
可以是tCHAR
(例如?q
),string1
(例如"q"、'q'或%q{q})或string1
和string
本身的递归定义的串联,这会导致像"foo" "bar"
、'foo' "bar"
或?f "oo" 'bar'
这样的字符串表达式被串联起来。
'ab' % (q{c})
,其中块 {c}
传递给 q
,但 q
并不存在(可能),因此出现了错误。 - Ahmad Sherif