Sylar Sylar - 3 months ago 9x
Ruby Question

How to use keep_if with string array

I'm trying to use keep_if in my Rails 5 app with Ruby 2.3.1.

a = ["a", "b", "c", "d" ]
b = ["b", "d"]

a.keep_if { |v| v=~ /["#{b}"]/ }
#=> ["b", "d"]

Real project:

a = ["apple", "banana", "orange"]
b = ["mangoes", "banana", "pear"]

a.keep_if { |v| v=~ /["#{b}"]/ }
#=> ["mangoes", "banana", "pear"]

What I expected:

#=> ["banana"]

I'm guessing some sort of regex to be used? How to get what I expected?


keep_if() deletes every element of self for which block evaluates to false. See Array#select!

If no block is given, an enumerator is returned instead.

Perhaps use something on the lines of:

c = a+b { |x| c.count(x) == 2 }.uniq   #=> ["banana"]
# (use .uniq > 2 for values that appear more than once)