Home > Enterprise >  String concatenation with constants in ruby 2.7.2
String concatenation with constants in ruby 2.7.2

Time:11-24

I'm trying to concatenate a constant into a string but I'm getting syntax error, unexpected unary , expecting end' (SyntaxError)`

This is an example of what I have to do:

NAME = "Jane"
def a_function
   s = 'Hi'   NAME  ' !'
   puts s
end

I know you can do "Hi #{NAME}!" but in my case the string has to be with single quotes.

How can I achieve this?

CodePudding user response:

You are missing a space between and ' !'.

This is a special case of confusing Ruby, because a single expression like x is actually a valid unary expression meaning just x, the same way as 1 means 1.

Because of this it's likely Ruby is interpreting your expression a b c, as a b c, which is invalid, and hence the error.

The fix:

s = 'Hi '   NAME   ' !'
                  ^------ Note the space here!
  •  Tags:  
  • ruby
  • Related