0
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?

2 Answers2

0

I don't understand your code particularly, but you may be having a common beginner's mistake to use destructive methods when you shouldn't. upcase! will return nil when no upcase takes place, and that may be causing your problem. Especially, you are doing upcase! on a string $main, and then doing upcase! on it again. If there were no upcasing in the first upcase!, then you would be calling the second upcase! on nil, which will raise an error. Even if there were upcasing in the first upcase!, the second upcasing will surely not take place, and you will get nil even in that case. It does not makes sense at all. Change upcase! to upcase.

By the way, I don't understand why you are using chomp correctly (instead of chomp!), but are using upcase! (instead of upcase). And I also don't understand why you are using the former chained after gets (which is okay) but are doing the latter within each condition in if elsif end block (which is not only redundant, but problematic).

Furthermore, it looks like you should be using case end instead.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • when I first wrote it, it said something like "unrecognized variable 'upcase'", but when I added ! then it worked. I am very new to programming so it is likely I am doing MANY things the wrong way, but thank your for the help. 私はまだ未熟者プログラマーだから、助けてくれましたありがとうございます。 – Will Von Wizzlepig Jul 18 '14 at 15:14
0

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 != "~"
infused
  • 24,000
  • 13
  • 68
  • 78