How do I collect a String and use it in an if?

Asked

Viewed 116 times

3

puts "Tem dinheiro? s/n"
x = gets.chomp

if x = s
  puts "Vou viajar"
else
  puts "Não vai ser dessa vez"
end
  • Gives error...conditional.Rb:3:in <main>': undefined local variable or method s' for main:Object (Nameerror)

1 answer

1


First, you have to organize the code, not just throw everything anyway.

Second, to compare a variable with a text is only possible if this text is expressed in its literal form, that is, it must be in quotation marks. Like a quote in a text.

Third, in the if is assigning a value to the variable with the =, to compare and obtain a true or false the correct operator is ==.

Thus:

puts "Tem dinheiro? s/n"
x = gets.chomp
if x == "s"
    puts "Vou viajar"
else
    puts "Não vai ser dessa vez"
end

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I suggest taking a course on programming before trying to write code randomly.

  • Thanks =) - I’m new here don’t know how do to print organized code...

  • I had tried this way with this same reasoning, gave the same error...I’m using Cloud 9

  • I showed it works, and it’s not very secret.

  • Yes. I thank you. A hug

  • 1

    = is attribution, needs to use == there

  • @Gabrielkatakura had not even attacked me to that, thank you

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.