ruby - 行为不当的案例陈述

标签 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,为什么它仍然运行第一种情况?

最佳答案

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

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

看看here .

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

关于ruby - 行为不当的案例陈述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3231726/

相关文章:

ruby - 编码和解码 ruby​​ 符号

ruby - Array 或 Hash 值的单一接口(interface)

ruby - ruby 中的控制台表格式

ms-access - 如何在 Access 中引用控件的属性

haskell - 为什么将具体类型传递给函数可以解决错误?

javascript - 在用方括号声明后立即用方括号索引是否有效的javascript?

ruby-on-rails - 错误无法加载此类文件 -- user_agent/browsers/playstation (LoadError)

ruby - 为每个请求清除 Firefox 中的 session (Watir 问题)

php - if-else 语句语法偏好

sql - 教义 : Use dash in field alias