Adding a space between variables

I made a program. Display names are not separated by a space. Does anyone know how to do this?

puts 'hello there, what is your forename?'
forename = gets.chomp
puts 'your middlename?'
middlename = gets.chomp
puts 'and your last name?'
surname = gets.chomp
puts 'so your full name is, ' + forename + middlename + surname + '. '
+4
source share
3 answers

The method itself gets.chompdoes not catch spaces. You will have to add them yourself.

Another Ruby way to do this is through a method join.

puts "So your full name is, #{[forename, middlename, surname].join(' ')}."

With David's suggestion to form a complete answer, use compactbefore joining to avoid an empty middlename and doubling the space.

puts "So your full name is, #{[forename, middlename, surname].compact.join(' ')}."
+3
source

There are no spaces, because you don't print them anywhere. You can interpolate variables (mind "double quotes):

puts "so your full name is,  #{forename} #{middlename} #{surname}."

Or explicitly concatenate with spaces ' ':

puts 'so your full name is, ' + forename + ' ' +  middlename + ' ' + surname + '. '
+3

Ruby ( , Ruby),

puts 'so your full name is, ' + forename + ' ' + middlename + ' ' + surname + '. '
0

Source: https://habr.com/ru/post/1599711/


All Articles