[转]ruby中gets 和 gets.chomp 区别

寻技术 Ruby编程 2023年07月10日 84

其区别主要体现在输出时

例如 :
 
print "how old are you?"
age=gets.chomp() 
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." #(这一整句都是在一行的)


>ruby test.rb
 how old are you?11
how tall are you?22
 how much do you weight?333
so ,you're 11 old,22 tall and 333  
heavy. 
即 gets 中包含了"\n" 而 gets.chomp 中不包括"\n"
#chomp方法是移除字符串尾部的分离符,例如\n,\r等...而gets默认的分离符是\n
关闭

用微信“扫一扫”