LRTHW练习十一

  紧跟前面学习的步伐,坚持学习!

  练习十一讲的是输入

  这里的输入是通过方法:gets.chomp

# 从窗口中输入数据
print "How old are you ?"
age =  gets.chomp

print "How tall are you?"
height = gets.chomp

print "How much do you weight?"
weight = gets.chomp

puts "So, you're #{age} old, #{height} tall and #{weight} heavy."

搜索有关资料最多的讨论时:gets与gets.chomp的比较,结果是:

两者在输入时,没有区别,通过实验

# 从窗口中输入数据
# change the gets.chomp to the gets
print "How old are you ?"
age =  gets

print "How tall are you?"
height = gets.chomp

print "How much do you weight?"
weight = gets

puts "So, you're #{age} old, #{height} tall and #{weight} heavy."

输出:

[ufindme@ufindme day5]$ ruby ex11b.rb 
How old are you ?112
How tall are you?223
How much do you weight?445
So, you're 112
 old, 223 tall and 445
 heavy.

gets和gets.chomp()都表示读入用户的输入并用于输出,但两者还是有所不同。输入的时候两者都没有区别,区别在于输出时取输入值得时候:

其中gets是得到的内容后,在输出时后面接着换行;而gets.chmop()得到的内容输出时后面不带空格和换行。

然而有人给出的解释是:

gets 中包含了" " 而 gets.chomp 中不包括" "

#chomp方法是移除字符串尾部的分离符,例如 , 等...而gets默认的分离符是
原文地址:https://www.cnblogs.com/ufindme/p/3956976.html