字符串连接如何在 ruby​​ 中工作?

How String concatenation works in ruby?

下面这行代码如何在 ruby​​ 中连接一个字符串?

2.1.0 :052 > value = "Kamesh" "Waran"
 => "KameshWaran" 

我知道“+”是 String class 上的一种方法,它连接传递的字符串。空格(' ')怎么可以是operator/method?

谁能详细说明空格 (' ') 是如何连接字符串的?

space 不是运算符。这仅适用于字符串 文字 ,并且只是文字语法的一部分,如双引号。如果你有两个字符串文字,它们之间只有 whitespace,它们会变成一个字符串。这是从后来的 C 版本中借用的约定。

irb(main):001:0> foobar = "foo" "bar"
=> "foobar"
irb(main):002:0> foo="foo"
=> "foo"
irb(main):003:0> bar="bar"
=> "bar"
irb(main):004:0> foo bar
NoMethodError: undefined method `foo' for main:Object
        from (irb):4
        from /usr/local/var/rbenv/versions/2.1.3/bin/irb:11:in `<main>'
irb(main):005:0>

如果您在此站点上进行搜索,您会得到答案。

发现时间: Why do two strings separated by space concatenate in Ruby?

Implementation details can be found in parse.y file in Ruby source code. Specifically, here.

A Ruby string is either a tCHAR (e.g. ?q), a string1 (e.g. "q", 'q', or %q{q}), or a recursive definition of the concatenation of string1 and string itself, which results in string expressions like "foo" "bar", 'foo' "bar" or ?f "oo" 'bar' being concatenated.