gpt4 book ai didi

ruby - 单行代码输出?

转载 作者:数据小太阳 更新时间:2023-10-29 08:46:12 26 4
gpt4 key购买 nike

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

我正在使用 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

最佳答案

使用#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

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.

关于ruby - 单行代码输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27989451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com