我对编程非常陌生,至少面向对象所以请温柔:)
我正在尝试创建预算程序,但我无法识别字符串。我有一个名为payperiod的变量,很简单,它将用于保存每周,每月等字符串值。我在这里做错了什么?
#!/usr/bin/env ruby # # Simple Budgeting Program # puts "Hi, I would like to develop a budgeting program for you..\n\n\n\n\n" puts "What is your budget type? \n \n \n You can say 'Monthly' 'Weekly' or 'Fortnightly' \n" payperiod = gets if payperiod == "Monthly" puts "You are paid monthly." end if payperiod == "Weekly" puts "You are paid Weekly" end if payperiod == "Fortnightly" puts "You are paid every two weeks!" end
答案 0 :(得分:1)
您忘记了按下提交答案的返回键:
2.1.0 :001 > mystring = gets
Monthly
=> "Monthly\n"
2.1.0 :002 > mystring.chomp
=> "Monthly"
2.1.0 :003 > correct_string = gets.chomp
Monthly
=> "Monthly"
答案 1 :(得分:1)
获取方法将获得"输入"键盘键。这意味着特殊字符 \ n 将被添加到字符串的末尾,因为这是表示"输入"键盘键。
因此,当您输入单词" Monthly"," Weekly"或"每两周一次"这个脚本真正捕获的是"每月\ n","每周\ n"或者"每两周\ n"。
因此,您的脚本必须使用chomp方法(由JCorcuera高配)来删除该字符。
如果你想使用chomp方法,你的脚本看起来像
payperiod = gets
if payperiod.chomp == "Monthly"
puts "You are paid monthly."
elsif payperiod.chomp == "Weekly"
puts "You are paid Weekly"
elsif payperiod.chomp == "Fortnightly"
puts "You are paid every two weeks!"
else
puts "Invalid option!"
end
如果您不想使用chomp,可以附加" \ n"
payperiod = gets
if payperiod == "Monthly\n"
puts "You are paid monthly."
elsif payperiod == "Weekly\n"
puts "You are paid Weekly"
elsif payperiod == "Fortnightly\n"
puts "You are paid every two weeks!"
else
puts "Invalid option!"
end
答案 2 :(得分:0)
获取获取字符串的代表。它返回用户输入的所有内容,包括他们没有意识到它们正在放入的内容.gets.chomp删除末尾的所有空格,以便它只返回您想要的字符串。如果用户输入'每月''每月'或'十分',那么将它包括在内也是一个好主意。
user_input:每月
mystring1 = gets
=> 'Monthly/n'
mystring2 = gets.chomp
=> 'Monthly'
mystring3 = gets.chomp.downcase
=> 'monthly'
mystring1 == 'monthly'
=> false
mystring1 == 'monthly'
=> false
mystring1 == 'monthly'
=> true