+ 3

What's wrong with this code?

# Ruby a = gets puts !(a) Suppose that a == false. The code outputs false! Who can explain how to make the NOT operator work?

24th Jul 2017, 2:15 AM
Erik Johanson
Erik Johanson - avatar
2 odpowiedzi
+ 5
when using gets a is a string input. Even if it is an empty string when checking it by itself as a comparison it will return true as a boolean because it exists. If a was equal to nil or false it would return false. Then you are using the not operator (!) to flip the result. a = false puts !(a) // outputs true a = nil puts !(a) // outputs true Even if you typed in nil or false as the input, a is still actually a string "nil" or "false" not the ruby keyword value of nil or false. When an object in ruby is set (even empty) and checked like (a) you're actually checking if that object exists not the value of the object. If it exists then true is returned, if the object is not set (nil) then false is returned. The not operator (!) just inverts, or flips, the true to false, or the false to true What you most likely want to do is compare a against some other string value. a = gets.chomp // chomp is needing to get rid of the '\n' character at the end of the input puts (a == "b") // this compares the value of a to the string "b" Here if b is input at the prompt it will return true.
24th Jul 2017, 2:55 AM
ChaoticDawg
ChaoticDawg - avatar
+ 13
a = gets => a is a string. In Ruby, any string is truthy. So, !(a) will always be false.
24th Jul 2017, 2:51 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar