Sayan Sayan - 1 year ago 57
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 =
File.readlines('demo.txt').each do |line|
line.slice! ", "
array.push line
array.each do|d|
puts d

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

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

Answer Source

There is ab\n in your array.

Instead of

array.each do|d|
    puts d

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