How String concatenation works in ruby? [duplicate]

二次信任 提交于 2019-12-24 11:36:40

问题


How the following line of code concatenates a string in ruby?

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

I understand that '+' is a method on String class which concatenates the strings passed. How the space(' ') can be the operator/method?

Can anyone elaborate how the space(' ') concatenate strings?


回答1:


The space is not an operator. This only works for string literals, and is just part of the literal syntax, like the double-quotes. If you have two string literals with nothing but whitespace between them, they get turned into a single string. It's a convention borrowed from later versions of 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>



回答2:


If you do a search on this site you get an answer.

Found on : 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.



来源:https://stackoverflow.com/questions/27763763/how-string-concatenation-works-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!