Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Basics (Retired) Ruby Strings Whitespace

Nicolas Hémidy
Nicolas Hémidy
8,481 Points

Issue with new line

Hello everyone, I try to build an easy quiz to learn how to use the basics of ruby but i struggle with the \n.

I coded that :

print "Please enter your name: "
name = gets
puts "Hello\s#{name}"
print "Do you want to answer my quiz ? : "
participation = gets
string = "#{participation}? That's cool !"
puts string

My problem is, when it prints string = "#{participation}! That's cool!", it prints it as that :

Yes

! That's cool !

Whereas, i would like it to be printed as :

Yes ! That's cool !

Could someone explain me why everything i put after {participation} go to a new line ?

I really thank you in advance, Nicolas

3 Answers

Hi Nicolas,

It is very common whitespace issues in Ruby that pushing invisible spaces to the next lines, you can ALWAYS use this "chomp" string after gets method to get rid of it, therefore every other languages has different kind of whitespaces and some issues but there are a lot of ways to do it better.

Let's try this: "gets.chomp" .

print "Please enter your name: "

name = gets.chomp

puts "Hello #{name}"
print "Do you want to answer my quiz? "

participation = gets.chomp 

string = "#{participation}? That's cool!"
puts string

More details - chomp string

-Salman

Nicolas Hémidy
Nicolas Hémidy
8,481 Points

Hello Salman,

Thanks for your answer. If i've well understood, the program understand "Yes + enter" when we type on our keyboard. It works with the chomp !

Thank you, Nicolas

Yeah, have you thought about if someone type to say "no"?

print "Please enter your name: "
name = gets.chomp
puts "Hello #{name}"
print "Do you want to answer my quiz? (yes/no): "
participation = gets.chomp 

if participation == "yes"
    puts "#{participation}? That's cool!"
elsif participation == "no"
    puts "Have a great day, maybe next time!"
else
    puts "I'm sorry. I did not get your answer. Please try again."
end

Hope that helps. :-)

Nicolas Hémidy
Nicolas Hémidy
8,481 Points

Yes it helps ! I did not yet discover the if/elsif/else part but i understand how it works. Thank you Salman