Arrays 包括?myVariable未按预期工作
我正在编写一个Ruby 1.9脚本,在使用数组的Arrays 包括?myVariable未按预期工作,arrays,ruby,Arrays,Ruby,我正在编写一个Ruby 1.9脚本,在使用数组的.include?方法时遇到了一些问题 这是我的整个代码块: planTypes = ['C','R','S']; invalidPlan = true; myPlan = ''; while invalidPlan do print "Enter the plan type (C-Commercial, R-Residential, S-Student): "; myPlan = gets().upcase; if
.include?
方法时遇到了一些问题
这是我的整个代码块:
planTypes = ['C','R','S'];
invalidPlan = true;
myPlan = '';
while invalidPlan do
print "Enter the plan type (C-Commercial, R-Residential, S-Student): ";
myPlan = gets().upcase;
if planTypes.include? myPlan
invalidPlan = false;
end
end
出于故障排除目的,我添加了打印语句:
while invalidPlan do
print "Enter the plan type (C-Commercial, R-Residential, S-Student): ";
myPlan = gets().upcase;
puts myPlan; # What is my input value? S
puts planTypes.include? myPlan # What is the boolean return? False
puts planTypes.include? "S" # What happens when hard coded? True
if planTypes.include? myPlan
puts "My plan is found!"; # Do I make it inside the if clause? Nope
invalidPlan = false;
end
end
因为我用硬编码字符串得到了正确的结果,所以我尝试了“{myPlan}”
和myPlan.to_
。但是我仍然得到一个false
结果
我不熟悉Ruby脚本,所以我猜我遗漏了一些明显的东西,但在回顾了类似的问题并检查了之后,我对它的运行方式不正确感到困惑。的
结果包含一个新行(\n
),如果打印我的计划,您可以看到它。检查:
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C\n"
添加以清除不需要的空白:
myPlan = gets().upcase.strip;
获取的结果
包括一个换行符(\n
),如果您打印myPlan,您可以看到该换行符。检查
:
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C\n"
添加以清除不需要的空白:
myPlan = gets().upcase.strip;
否决票是否由于缺少\n
字符而导致?我希望在投票时得到一些反馈。谢谢。否决票是因为缺少\n
字符吗?我希望在投票时得到一些反馈。谢谢