user3043926 user3043926 - 7 months ago 18
Ruby Question

How can I make script work in Ruby?

I am new to Ruby.
I need to make this script work:

puts "Do you like cats?"
ask = gets

def ask(n)

if ask == yes
return "I do too"
end

if ask == no
return "Dogs are better"
end
end

puts "#{ask(n)}"


Error message is :


pracif.rb:15:in
<main>': undefined local variable or method
n' for
main: Object (NameError)

Answer

Here's a script that would work for you :

puts "Do you like cats?"
answer = gets

def ask(n)

 if n == 'yes'
   return "I do too"
 end

 if n == 'no'
   return "Dogs are better"
 end
end

puts "#{ask(answer.downcase.chomp)}"

Explaination

  1. As the error said you were trying to pass in a variable n which was not defined

  2. Secondly you have a method name ask same as variable name. I've renamed the variable to answer instead

  3. Thirdly, enclose yes and no in quotes

  4. And finally, since you are using gets a \n gets appended like yes\n so none of your conditions would match. So i've used chomp to remove \n. And also used downcase to make input case insensitive.