案例陈述未按预期运作

我有一个名为Exercises.rb文件

 def ask(prompt) print prompt, ' ' $stdout.flush s = gets return s end def myreverse(s) aux="" for i in 0..s.length-1 aux=s[i] + aux end return aux end def mywordreverse(s) aux=[] s=s.split(" ") for i in 0..s.length-1 aux.unshift(s[i]) end return aux.join(" ") end def choose(s,option) case option when 1 then print myreverse(s) when 2 then print mywordreverse(s) when 3 then print "hello" else print "You gave me #{option} -- I have no idea what to do with that." end end s=ask("Write a string to reverse: ") option=ask("Choose an option. 1 - Reverse string. 2 - Reverse String words : ") choose(s,option) 

我总是得到You gave MYCHOSENOPTION -- I have no idea what to do with that. ,无论我选择什么选项。 如果我在比较1的case放置一个if ,它似乎与我的字符串的选项不匹配。

FWIW,这是我写这个程序的方式:

 def ask(prompt) print "#{prompt} " gets.chomp end def myreverse(s) s.reverse end def mywordreverse(s) s.split(' ').reverse.join(' ') end def choose(s,option) case option when 1 then puts myreverse(s) when 2 then puts mywordreverse(s) when 3 then puts "hello" else puts "You gave me #{option}; I don't know what to do with that." end end $stdout.sync str = ask("Write a string to reverse: ") option = ask("Choose an option:\n1: Reverse string\n2: Reverse String words\n>") choose(str,option.to_i) 

笔记:

  1. 方法中的最后一个表达式返回值; 在Ruby中几乎不需要使用return
  2. 存在用于反转字符串和数组的内置方法。 (我知道如果你这样做是为了练习。)
  3. 使用for迭代Ruby中的数组或字符串很麻烦。 相反,你应该使用

     my_str.each_char do |char| # use the single-character string `char` here end my_array.each do |item| # use the item here end 
  4. 您可以使用$stdout.sync强制输出始终被刷新。

  5. 您需要在字符串上使用chomp来删除用户按Enter键时始终包含的尾随换行符。
  6. 正如@robbrit所指出的,你的问题的核心是gets的返回值是一个String,你将它与Fixnum进行比较。 我在上面的代码中使用了to_i将字符串转换为整数进行比较。
  7. 我已经使用了puts而不是print来输出,所以我在结尾处得到一个换行符,并且不会让用户将下一个命令提示符放在与输出相同的行上。

试试这个:

  case option.to_i # rest of your code... 

在Ruby中, 1 == "1" (或者更具体地说,在case语句的case1 === "1" )总是计算为false 。 在进行比较之前,您需要转换其中一个以使它们是相同的类型。 您为option传入的值可能是String ,因此对于整数的任何比较都将失败。