0

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.

Community
  • 1
  • 1
Iron3eagle
  • 1,077
  • 7
  • 23
  • Is the down vote due to missing the `\n` character? Would love some feed back when given down vote. Thanks. – Iron3eagle Feb 15 '16 at 18:57

1 Answers1

4

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
"C\n"

Add strip to clean out the unwanted whitespace:

myPlan = gets().upcase.strip;
Enter the plan type (C-Commercial, R-Residential, S-Student): C
"C"
Kristján
  • 18,165
  • 5
  • 50
  • 62