简体   繁体   中英

Misbehaving Case Statement

I'm messing around in Ruby some more. I have a file containing a class with two methods and the following code:

if __FILE__ == $0

  seq = NumericSequence.new

  puts "\n1. Fibonacci Sequence"
  puts "\n2. Pascal\'s Triangle"
  puts "\nEnter your selection: "
  choice = gets
  puts "\nExcellent choice."

  choice = case
  when 1
    puts "\n\nHow many fibonacci numbers would you like? "
    limit = gets.to_i
    seq.fibo(limit) { |x| puts "Fibonacci number: #{x}\n" }
  when 2
    puts "\n\nHow many rows of Pascal's Triangle would you like?"
    n = gets.to_i
    (0..n).each {|num| seq.pascal_triangle_row(num) \
       {|row| puts "#{row} "}; puts "\n"}
  end

end

How come if I run the code and supply option 2, it still runs the first case?

Your case syntax is wrong. Should be like this:

case choice
  when '1'
    some code
  when '2'
    some other code
end

Take a look here .

You also need to compare your variable against strings, as gets reads and returns user input as a string.

Your bug is this: choice = case should be case choice .

You're providing a case statement with no "default" object, so the first clause, when 1 , always returns true.

Effectively, you've written: choice = if 1 then ... elsif 2 then ... end

And, as Mladen mentioned, compare strings to strings or convert to int: choice = gets.to_i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM