行为不端的案件陈述

时间:2010-07-12 19:46:43

标签: ruby syntax

我在Ruby中搞砸了一些。我有一个包含两个方法的类的文件和以下代码:

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

如果我运行代码并提供选项2,它仍会运行第一种情况?

2 个答案:

答案 0 :(得分:5)

您的case语法错误。应该是这样的:

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

看看here

您还需要将变量与字符串进行比较,因为gets读取并将用户输入作为字符串返回。

答案 1 :(得分:1)

您的错误是:choice = case应为case choice

您提供的case语句没有“default”对象,因此第一个子句when 1始终返回true。

实际上,你写过:choice = if 1 then ... elsif 2 then ... end

并且,正如Mladen所提到的,将字符串与字符串进行比较或转换为int:choice = gets.to_i