Sayan Sayan - 6 months ago 12
Ruby Question

Checking if an element belongs to an array in Ruby

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

a, b
c, d


The ruby code goes as follows

array = Array.new
File.readlines('demo.txt').each do |line|
line.slice! ", "
array.push line
end
array.each do|d|
puts d
end

if array.include? 'ab'
puts "correct" #this is not printed
end


How do I check if the array contains the element 'ab'?

Answer

There is ab\n in your array.

Instead of

array.each do|d|
    puts d
end

use inspect to check the values,

p array
#=> ["ab\n", "cd"]

To fix the issue, use chomp on line

File.readlines('b.txt').each do |line|   
    line = line.chomp
    ...
end