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.

1
  • Is the down vote due to missing the \n character? Would love some feed back when given down vote. Thanks. Commented Feb 15, 2016 at 18:57

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.