gets和gets.chomp的区别

本文介绍了Ruby语言中gets与gets.chomp两个方法的区别。通过两个具体的示例对比了它们在读取输入时的不同表现,即是否保留换行符。这对于理解用户输入处理流程非常有用。

例子1:

print "How old are you ?"

age = gets.chomp()

print "How tall are you ?"

height = gets

print "How much do you weight ?"

weight = gets.chomp()

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

输出的内容如下所示:

How old are you ?11

How tall are you ?23

How much do you weight ?23

so, you're 11 old, 23

 tall  and 23 heavy.

例子2:

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."

输出内容如下:

How old are you ?11

How tall are you ?23

How much do you weight ?23

so, you're 11 old, 23 tall  and 23 heavy.

总结:gets和gets.chomp的区别在于,gets的input中包括\n,而gets.chomp的input中不包括\n。

转载于:https://www.cnblogs.com/perish/archive/2012/06/30/2571274.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值