Array.include? myVariable not working as expected
I am coding a Ruby 1.9 script and I'm running into some issues using the .include?
method with an array.
This is my whole code block:
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
For troubleshooting purposes I added print statements:
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
Since I was getting the correct result with a hard-coded string, I tried "#{myPlan}"
and myPlan.to_s
. However I still get a false
result.
I'm new to Ruby scripting, so I'm guessing I'm missing something obvious, but after reviewing similar question here and here, as well as checking the Ruby Doc, I'm at a loss as to way it's not acting correctly.
The result of gets
includes a newline ( n
), which you can see if you print myPlan.inspect
:
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"Cn"
Add strip
to clean out the unwanted whitespace:
myPlan = gets().upcase.strip;
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C"
链接地址: http://www.djcxy.com/p/25692.html
上一篇: 按键整数重新排序整数数组