Array.include? myVariable无法按预期工作

我正在编写一个Ruby 1.9脚本,我遇到了一些使用.include?问题.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脚本编程的新手,所以我在猜测我错过了一些明显的东西,但是在查看这里和这里的类似问题以及检查Ruby Doc之后,我不知道它的行为是否正确。


结果gets包括换行符( n ),你可以看到,如果你打印myPlan.inspect

Enter the plan type (C-Commercial, R-Residential, S-Student): C
"Cn"

添加strip以清除不需要的空白:

myPlan = gets().upcase.strip;
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C"
链接地址: http://www.djcxy.com/p/25691.html

上一篇: Array.include? myVariable not working as expected

下一篇: How to get the users input and check against the items in an array?