这是我的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
我做错了什么?
答案 0 :(得分:3)
一些更正:
answer
。returns
未定义,应该是return
。尝试如下并遵循一本好的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)