When I compared it with the character string from the standard input, it didn't work for some reason. The cause and solution are described as a memorandum.
The gets
method is a method for receiving strings from standard input.
If you try to compare the input string obtained using this method with another string
I didn't get the results I expected.
input = gets #Enter hoge
bool = (input == 'hoge')
print bool
false
I should be comparing strings with the same value, but for some reason false
is returned.
After checking, it seems that the gets
method adds ** line feed code (\ n) ** at the end by default.
input = puts #Enter hoge
p input
"hoge\n"
I was trying to compare with the line feed code included, so it seems that it was played even if I compared it.
It seems that I should delete the line feed code at the end, so I checked it and found
There is a chomp
method as a method for that,
When I used this, I got the expected result!
input = gets.chomp #Enter hoge
bool = (input == 'hoge')
print bool
true
I thought that chomp
was an abbreviation for something, and when I looked it up, the answer in teratail was helpful.
What does chomp stand for?
It contains a lot of speculation Originally, there was chop and I was able to erase the last character. It was a (Unix) manner that the end of the text file ends with a line break, so this was fine. There is a problem that there is no line break at the end and there are environments where it is not a single character A "remove trailing newline" function has been added and it is chomp because it is for multiline of chop.
It seems that the chomp
method is used to delete the line feed code from the last character of chop
.
https://stackoverflow.com/questions/21504202/why-is-stringchomp-named-like-this
Recommended Posts