user3472065
user3472065

Reputation: 1389

Check if an element is included in an array in RUBY

I would like to write a compact version that checks if an element is included in an array

I have these data. "out_cmd" is an array like this:

aaaaaa
bbbbbb
cccccc
dddddd

and "list" is another array like:

cccccc
aaaaaa

For each line of "out_cmd" I would like to know if it is contained in "list". If it is the case, skip the line. Here my (not working) code:

outputs=Array.new
out_cmd.each_line { |line|
    next if line.include?"*"
    next if list.include?(line)
    "DO SOMETHING"
}

Upvotes: 1

Views: 84

Answers (3)

the Tin Man
the Tin Man

Reputation: 160551

@wolf mentioned this but didn't explain it in a way that shows what's happening.

If you have:

out_cmd = %w[
  aaaaaa
  bbbbbb
  cccccc
  dddddd
]

list = %w[
  cccccc
  aaaaaa
]

You can easily see what they have in common:

out_cmd & list # => ["aaaaaa", "cccccc"]

Or what the differences are:

out_cmd - list # => ["bbbbbb", "dddddd"]

Upvotes: 0

daremkd
daremkd

Reputation: 8424

list = File.readlines('list.txt').map(&:chomp) #=> ["aaaaaa", "bbbbbb", "cccccc", "dddddd"]

File.readlines('out_cmd.txt').map(&:chomp).each do |line|
  next if list.include?(line)
end

Upvotes: 1

Cristian Lupascu
Cristian Lupascu

Reputation: 40536

If out_cmd and list are arrays, then you can do:

out_cmd - list

to find the lines in out_cmd which are not present in list.

Therefore, you can write the following code:

(out_cmd - list).each { |line|
  # this iterates every line in out_cmd which is not in list
  p line
}

Note: from your usage of out_cmd, it is not an array, as you claim, but probably a string which contains more lines. If that's the case, first convert it to an array like this: out_cmd.lines.map(&:chomp)

Upvotes: 4

Related Questions