我还在用 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,为什么它仍然运行第一种情况?
最佳答案
您的case
语法错误。应该是这样的:
case choice
when '1'
some code
when '2'
some other code
end
看看here .
您还需要将您的变量与字符串进行比较,因为 gets
读取用户输入并将其作为字符串返回。
关于ruby - 行为不当的案例陈述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3231726/