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

How to remove spacing after displaying input (gets)

Hello programmers of all levels!

So I've got a question. I'm learning Ruby and I am a little confused how to remove some random spacing after displaying input. In example;

puts "Hello! What's your name?"
name = gets
puts "Oh, nice to meet you #{name}!"

The result is actually;

Oh, nice to meet you Noah        #This.....
!          #... And this are what I am talking about
=> nil

I figured out how to do it once, but as I write larger programs, it seems to become more and more complicated to keep it from adding such spacing.

I figure there is a solution somewhere. And thanks to everyone who offers a helping hand. :)

Edit: So the TTH forums have an awkward auto-rearrange of, coincidentally, where I put my code. I hope it is readable, and, if someone knows of proper forum posting of code ([CODE][/CODE] aren't working, as can be used elsewhere), I'd also be grateful to know that as well.

Thanks again!

2 Answers

Joseph Kato
Joseph Kato
35,340 Points

Hi Noah,

This post should help with code-formatting: Posting Code to the Forum.

With regards to your actual question, are you getting a newline before the exclamation point? If so, I think the .chomp method may be of use. For instance:

name = gets.chomp

Hello, and thanks for a double dose of help!

As for my code, the exclamation is getting a newline. Ahh, I think I see now.

I know about chomp, but maybe if I display a variable (ie, #{}) it will throw off the rest of the code.

I'll give it a try and give an update.

Thanks!

Edit: Bingo, .chomp fixes everything. I think I remember now, that a string without .chomp returns as 'My String\n'.

Thanks, Joseph!