Search code examples
rubystringspace

How String concatenation works in ruby?


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?


Solution

  • 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>