好的,这是我第一天学习,我正在尝试用Ruby创建一个非常基本的问卷。
例如,这将是我的代码:
print "What is your name? "
name = gets
puts "Hello #{name}, Welcome."
print "What year were you born in?"
year = 2014
year1 = gets.chomp.to_i
year2 = year-year1
puts "Ok. If you were born in #{year1}, then you are probably #{year2} years old."
现在,如果我为我的名字输入“Joe”,为我的生日输入“1989”,它会给我以下几行......
你好乔 ,欢迎。
确定。如果你出生于1989年,那么你可能已经25岁了。
我真的很困惑这两个字符串有什么不同。
答案 0 :(得分:3)
您对处理用户输入年份的方式有了正确的想法。当他们在提示符下键入“Joe”时,会导致字符串值“Joe \ n”被分配给name
变量。要从字符串末尾删除换行符,请使用chomp
方法。这会将行更改为name = gets.chomp
。
您可能还希望将输入显式转换为字符串。如果用户使用control-D结束输入,则gets
将返回nil
而不是空字符串,然后当您致电NoMethodError
时,您将获得chomp
它。最终代码为name = gets.to_s.chomp
。
答案 1 :(得分:1)
当你调用“gets”时,它实际上默认将换行符“\ n”附加到字符串的末尾。我可以建议在get的末尾添加“chomp”方法来删除新行吗?
新答案:
print "What is your name? "
name = gets.chomp
puts "Hello #{name}, Welcome."
print "What year were you born in?"
year = 2014
year1 = gets.chomp.to_i
year2 = year-year1
puts "Ok. If you were born in #{year1}, then you are probably #{year2} years old."