Nick5a1
Nick5a1

Reputation: 917

Ruby delete_if multiple values - only first value being deleted

words.delete_if do |x|
  x == ("a"||"for"||"to"||"and")
end

words is an array with many words. My code is deleting "a" but not deleting "for", "to" or "and".

Upvotes: 2

Views: 2547

Answers (3)

Salil
Salil

Reputation: 47482

Just do

words - ["a", "for", "to", "and"]

Example

words = %w(this is a just test data for array - method and nothing)
 => ["this", "is", "a", "just", "test", "data", "for", "array", "-", "method", "and", "nothing"] 
words = words - ["a", "for", "to", "and"]
 => ["this", "is", "just", "test", "data", "array", "-", "method", "nothing"] 

Upvotes: 7

Aditya Kapoor
Aditya Kapoor

Reputation: 1570

If you run "a" || "b" in irb then you will always get "a" because it is a non null value and it would be returned by || always.. In your case "a"||"for" will always evaluate for "a" irrespective of the other values in the array.. So this is my alternate solution to your question

w = %W{a for to end}

words.reject! { |x| w.include?(x) }

Upvotes: 5

oldergod
oldergod

Reputation: 15010

May this will help you

words.delete_if do |x|
  %w(a for to and).include?(x)
end

Upvotes: 8

Related Questions