1

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?

Kamesh
  • 1,435
  • 1
  • 14
  • 27

2 Answers2

3

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>
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
1

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.

Community
  • 1
  • 1
Luis Tellez
  • 2,785
  • 1
  • 20
  • 28