Ruby if,elsif和else条件语句错误没有输出

时间:2015-10-12 21:09:30

标签: ruby

这是我的Ruby代码。当我执行它时,它询问问题,然后当我没有或是,没有任何反应。它结束了。

puts "Do you like cats (Yes or No)?"
ans = gets.chomp

def answer(ans)
  if ans == "Yes" || ans == "yes"
    returns "Ken does too"
  elsif ans == "No" || ans == "no"
    returns "Dogs are better"
  else 
    returns "It's hard to decide"
  end
end

我做错了什么?

4 个答案:

答案 0 :(得分:3)

一些更正:

  1. 您根本没有调用方法answer
  2. 确保在调用方法之前定义方法。
  3. 关键字returns未定义,应该是return
  4. 请务必调用您打算使用的方法。
  5. 尝试如下并遵循一本好的Ruby书。这可能是一个好的开始:https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md

    def answer(ans)
      if ans == "Yes" || ans == "yes"
        return "Ken does too"
      elsif ans == "No" || ans == "no"
        return "Dogs are better"
      else 
        return "It's hard to decide"
      end
    end
    
    puts "Do you like cats (Yes or No)?"
    ans = gets.chomp
    
    puts answer(ans)
    

答案 1 :(得分:1)

您没有在任何地方调用answer()方法。此外,returns不正确(return是)。在Ruby中,我们试图避免显式返回。您想使用puts打印字符串输出:

 puts "Do you like cats (Yes or No)?"
    ans = gets.chomp

    def answer(ans)
      if ans == "Yes" || ans == "yes"
          puts"Ken does too"
      elsif ans == "No" || ans == "no"
          puts"Dogs are better"
      else
          puts"It's hard to decide"
      end
    end

    answer(ans)

答案 2 :(得分:0)

在控制语句中使用print将避免在输出中添加额外的行。

Difference Between print and puts in ruby

def answer(ans) if ans == "Yes" || ans == "yes" print "Ken does too" elsif ans == "No" || ans == "no" print "Dogs are better" else print "It's hard to decide" end end

puts "Do you like cats (Yes or No)?" ans = gets.chomp

puts answer(ans)

答案 3 :(得分:-1)

使用return代替returns,或者更好地使用" ruby​​-way"就是这样:

puts "Do you like cats (Yes or No)?"
ans = gets.chomp

def answer(ans)
  if ans == "Yes" || ans == "yes"
    "Ken does too"
  elsif ans == "No" || ans == "no"
    "Dogs are better"
  else 
    "It's hard to decide"
  end
end

puts answer(ans)