Search code examples
rubyif-statementwhile-loopupcase

.upcase! makes if statement fail to work properly


begin
puts "Enter selection:\n\n"
$main = gets.chomp

        if $main.upcase! == "A"
                    call_function_1
        elsif $main.upcase! == "B"
                    call_function_2
        end

end while $main != "~"

With the code as it is, entering A runs call_function_1, but entering B seems to be ignored.

The issue appears to be the .upcase! , as when I remove it, it works fine... why?


Solution

  • You should be using upcase, not upcase!. I would also use a case statement instead of the if block.

    begin
      puts "Enter selection:\n\n"
    
      input = gets.chomp
    
      case input.upcase
      when 'A'
        call_function_1
      when 'B'
        call_function_2
      end
    
    end while $main != "~"