Method "include?" returning false when there is a character in the Ruby string

Asked

Viewed 198 times

3

I’m a beginner in Ruby and I’m trying to create a Hangman game to test my language skills. In a part of the code, I need to get a letter chosen by the user and check if that letter is present in the word to be found.

To perform this check, I am using the string method include?, but this method is returning false even when the letter exists in the word. To demonstrate this, I created an example of code below:

print "Digite uma palavra: "
WORD = gets.downcase           # A palavra que estou digitando é "bola"

print "Digite uma letra: "
char = gets.downcase          

puts WORD.include? char

In this example, if the user type in the second gets the letter "a", the method returns true, but if the user type the letter "b","o" or "l", the method returns false.

Why does this happen? How can I solve the problem?

  • For those who want to know, I’m using the version ruby 2.6.5.

1 answer

4


This is because gets returns not only the typed text, but also the character \n corresponding to ENTER that you type. This can be seen if you check the size of the string and its codepoints*:

print "Digite uma palavra: "
WORD = gets.downcase
p WORD
puts WORD.length
print WORD.codepoints

If you type "ball" and give ENTER, the exit will be:

"bola\n"
5
[98, 111, 108, 97, 10]

That is, the string size is 5, because it corresponds to bola\n (the 4 letters of the word "ball" plus the \n which corresponds to the ENTER).

Through the codepoints we can see that the last character is the 10, which in fact corresponds to the \n.


So when you type the letter "a," actually gets returns the string a\n. And like the string WORD contains the value bola\n, de facto a substring a\n is included in it.

But if you type the letter "b," it becomes b\n, and this substring is not included in the string bola\n. The same goes for the letters "o" and "l".

One way to solve it is to get rid of this \n, using the method chomp:

print "Digite uma palavra: "
WORD = gets.chomp.downcase

print "Digite uma letra: "
char = gets.chomp.downcase          

puts WORD.include? char

* To better understand what a Codepoint is, see this question.

And in fact gets uses the variable value $/ (input record separator), which is one of many predefined variables and whose value default is \n. But this can be changed, if you want.

  • 1

    Thank you, that’s exactly what I need!

Browser other questions tagged

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