2

How can I get output on a single line? Right now the name is on the first line and age comes in the next line.

I am using print instead of puts but still NOT getting the right output.

Ruby Code:

print "Please enter your name: ";
name = gets;

print "Please enter your age: ";
age = gets;
print "Entered details are: ",name, age;

Running it:

O/P:
Please enter your name: Tony Stark
Please enter your age: 35
Entered details are: Tony Stark
35
0

1 Answer 1

3

Use the #chomp method

name = gets.chomp # instead of name = gets
age = gets.chomp # instead of age = gets

I rewrite the code :

print "Please enter your name: "
name = gets.chomp

print "Please enter your age: "
age = gets.chomp
print "Entered details are: ",name, " ", age, "\n"

and ran it :

[arup@Ruby]$ ruby a.rb
Please enter your name: arup
Please enter your age: 27
Entered details are: arup 27
[arup@Ruby]$

#chomp

Returns a new String with the given record separator removed from the end of str (if present). If $/ has not been changed from the default Ruby record separator, then chomp also removes carriage return characters (that is it will remove \n, \r, and \r\n).

#gets

Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line.

Sign up to request clarification or add additional context in comments.

2 Comments

Good answer. I could add that the separator (new line character) is added to the end of the string, because you press the Enter when you answer for the questions.
@Archetylator You could add it to my answer too.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.