I'm trying to figure out how to check if an element belongs to an array using ruby. I'm reading from a file (say demo.txt) which has comma separated pairs in each line. I'm concatenating these two pairs and pushing it into an array. Later I need to check if a specific value belongs to the array. I can see the array is populated successfully but the second check is unsuccessful, i.e. it can't find the element in the array. 'My demo.txt' is as follows
array = Array.new
File.readlines('demo.txt').each do |line|
line.slice! ", "
if array.include? 'ab'
puts "correct" #this is not printed
ab\n in your array.
array.each do|d| puts d end
use inspect to check the values,
p array #=> ["ab\n", "cd"]
To fix the issue, use
File.readlines('b.txt').each do |line| line = line.chomp ... end