tags:

views:

42

answers:

2

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?

+1  A: 

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

glenn jackman
+5  A: 

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.

Mladen Jablanović
Don't forget to chomp: `case choice.chomp`
glenn jackman
Another good example for Ruby case statements: http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#S5
bta