Reputation: 6837
I just started learning how to code and I am following along Chris Pine's tutorial on Ruby. I completed an exercise that had me print out my first name then my middle name and then my last name and then finally had me greet me using my full name. I did everything correctly except at the very end I printed out my full name like this: ParkerJacobsPreyer
I was just wondering how to make sure the output of those variables would be spaced correctly? Here is the relevant line of code:
puts 'Well it was great to meet you ' + name + middleName + lastName
Upvotes: 1
Views: 6381
Reputation: 84363
If we're being thorough, you can also do:
first_name, middle_name, last_name = %w[John Q. Public]
msg = "It was great to meet you, %s %s %s.\n"
printf msg, first_name, middle_name, last_name
If you want to just be silly about it, you can even do this:
'It was great to meet you, ' << %w[John Q. Public].join(' ') + '.'
What makes Ruby cool is that you can use different expressions that are functionally equivalent, but semantically different. This frees you up to express your intent on a higher level.
Upvotes: 0
Reputation: 66837
String#% would be another alternative:
puts "Well it was great to meet you %s %s %s." % [name, middleName, lastName]
Upvotes: 3
Reputation: 7074
There are several ways. If you haven't gotten into string interpolation yet, the simplest way would be:
puts 'Well it was great to meet you ' + name + ' ' + middleName + ' ' + lastName
Upvotes: 2
Reputation: 239301
Instead of using addition to concatenate the strings, use string interpolation:
puts "Well it was great to meet you #{name} #{middleName} #{lastName}."
Note that for the #{variable}
syntax to work, you must use double quotes ("
) instead of single quotes ('
).
Upvotes: 7