1

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?

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget to chomp: case choice.chomp
Another good example for Ruby case statements: ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#S5
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.