Ruby 比较这两个值是否不存在
我正在尝试做什么
在我的模型中,我只想选择不等于(a 或 b)的项目。所以我这样做了,效果很好。
# 这有效
选择{|项目 | item.attribute != a}.select {|项目 | item.attribute != b}
问题
这种链接是有效的,但是还有另一种写法吗?
如果我还想检查 c 和 d 会发生什么?我会在某处添加一些数组吗?
我不会继续束缚吧?
跟进问题select
行将在我的模型中工作,但是当我尝试将 reject
行放入我的模型中时,我得到了 #未定义方法拒绝。
类模型 < ActiveRecord::Base
def self.foo
arr = [a,b]
拒绝 { |项目 | arr.include?(item.attribute)}
end
end
我猜 ActiveRecord 不理解 reject
? ActiveRecord 是否有类似于 SQL NOT LIKE
的方法?
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 chaining 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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们会说
items
是您正在使用#select
的项目数组。这会将您的选择反转为拒绝,但拒绝等于(a 或 b)的项目。
We'll say that
items
is your array of items that you are using#select
on.This reverses your select into reject, but rejects the items that ARE equal to (a or b).