DamonT
DamonT

Reputation: 15

Ruby question: syntax error whilst using gets

I am attempting to run the following program, which will give out a simple greeting taking user input. However, whenever I run the code I get the following message:

syntax error, unexpected tSTRING_BEG, expecting do or '{' or '('

I've tried replacing the single quote marks with doubles, and I've also tried placing '()' around the variable names.

puts 'First name:  '
first_name = gets.chomp
puts 'Middle name:  '
middle_name = gets.chomp
puts 'Surname:  '
surname = gets.chomp

puts "Greets to you," + first_name + middle_name + surname "! Welcome to Valhalla!"

Upvotes: 0

Views: 70

Answers (2)

spickermann
spickermann

Reputation: 106802

@eux already gave a correct answer to the syntax error in your example.

I just want to show another way to generate the expected output. It's a common Ruby idiom to use string interpolation instead of string concatenation. With string interpolation, you can generate your output like this

puts "Greets to you, #{first_name} #{middle_name} #{surname}! Welcome to Valhalla!"

String interpolation has many advantages – as described in this answer and its comments. In the context of your question the pros are:

  • It is shorter
  • It is much clearer where to put whitespace
  • And It is overall easier to read and understand

Upvotes: 1

eux
eux

Reputation: 3282

You missed a + before ! Welcome to Valhalla! at the last line:

puts "Greets to you," + first_name + middle_name + surname + "! Welcome to Valhalla!"

Upvotes: 0

Related Questions