代码输出单行?

时间:2015-01-16 17:26:49

标签: ruby

如何在一条线上获得输出?现在名字在第一行,年龄在下一行。

我使用的是print而不是puts,但仍未获得正确的输出。

Ruby代码:

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

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

运行它:

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

1 个答案:

答案 0 :(得分:3)

使用#chomp方法

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

我重写了代码:

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

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

并运行它:

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

#chomp

  

返回一个新的String,其中从str的结尾(如果存在)中删除了给定的记录分隔符。如果$ /尚未从默认的Ruby记录分隔符更改,则chomp也会删除回车符(即它将删除\ n,\ r和\ r \ n)。

#gets

  

返回(并且分配给$_ )ARGV(或$ *)中文件列表中的下一行,如果命令行中没有文件,则返回标准输入