Reputation: 21
Here is my Ruby code. When I execute it, it asks the question, then when I put no or yes, nothing happens. It just ends.
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
What am I doing wrong?
Upvotes: 0
Views: 301
Reputation: 3268
Using print
in your control statement will avoid adding an extra line to your output.
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)
Upvotes: 0
Reputation: 129
Use return
instead of returns
, or better the "ruby-way" would be this:
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)
Upvotes: -1
Reputation: 7136
You did not call your answer()
method anywhere. Also, returns
is incorrect (return
is). In Ruby, we try to avoid explicit return. You want to print the string output using 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)
Upvotes: 1
Reputation: 38645
A few corrections:
answer
at all.returns
is undefined, it's supposed to be return
.Try as follows and follow a good Ruby book. Here might be a good start: 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)
Upvotes: 3