开发者

Ruby comparing if these 2 values DO NOT exist

What I'm trying to do

In my Model, I want to select only the items that are NOT equal to (a or b) to. So I did this which works.

# This works

select { | item | item.attribute != a}.select {| item | item.attribute != b}

Question

This c开发者_如何转开发haining works, but is there a another way of writing this ?

What happens if I wanted to also check c and d ? Would I add some array somewhere ?

I wouldn't keep chaining would I ?

Follow Up Question

The select line will work in my model, but when I try to put the reject line in my model I get a undefined method reject for #<Class>

class Model < ActiveRecord::Base

def self.foo

arr = [a,b]

reject { | item | arr.include?(item.attribute)}

end

end

I'm guessing ActiveRecord does not understand reject ? Does ActiveRecord have a method that is similar to SQL NOT LIKE ?


We'll say that items is your array of items that you are using #select on.

arr = [a, b] # or [a, b, c, d]
items.reject { |item| arr.include?(item.attribute) }

This reverses your select into reject, but rejects the items that ARE equal to (a or b).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜