我正在编写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 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_s
。但是我仍然得到false
结果。
我是Ruby脚本的新手,所以我猜测我错过了一些明显的东西,但在审核了类似的问题here和here之后,以及检查Ruby Doc,我不知道其行为不正确。
答案 0 :(得分:4)
gets
的结果包含换行符{\n
),如果您打印myPlan.inspect
,则可以看到该行:
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C\n"
添加strip
以清除不需要的空格:
myPlan = gets().upcase.strip;
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C"