user2066488
user2066488

Reputation: 21

Ruby if, elsif, and else conditional statement error with no output

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

Answers (4)

Casey Robinson
Casey Robinson

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

ruby life questions
ruby life questions

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

Cyzanfar
Cyzanfar

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

vee
vee

Reputation: 38645

A few corrections:

  1. You are not calling the method answer at all.
  2. Make sure you define the method before calling it.
  3. The keyword returns is undefined, it's supposed to be return.
  4. Make sure to call the method you intend to use.

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

Related Questions