[Ruby] About gets and gets.chomp

1 minute read

It’s not a big deal to write code in Ruby, but I overlooked it and got hooked.

I thought I knew the difference between gets and gets.chomp

I thought I knew that gets had a newline code at the end and gets.chomp didn’t have a newline code, but …

input = gets
array=['cat','cat1','cat2','cat3','dog','tomcat']
array.each do |a|
  puts a.include?(input)
end

Then, all return with false.
As I wrote at the beginning, gets has a newline code at the end, so the include? Method is looking for a match with cat plus newline code, so it will be false.

input = gets
array=[]
for i in 1..6 do
  array_input=gets
  array << array_input
end
array.each do |a|
  puts a.include?(input)
end

If you enter cat, cat1, … and the same elements as the above code array in order, only the first and last (cat and tomcat) will be returned as true. (I was addicted to this)
This means that if the value entered in gets in the part that is being turned in the for statement ends with cat, the line feed code will be inserted at the end, so it will match. Anything that does not end with cat is recognized as inconsistent.

answer

If input = gets.chomp, the line feed code will not be included in the first input character string, so the intended result will be obtained.

input = gets.chomp
array=['cat','cat1','cat2','cat3','dog','tomcat']
array.each do |a|
  puts a.include?(input)
end

Tags:

Updated: