我使用Ruby on Rails 3.2.9和Ruby 1.9.3。我有一个符号数组和一个模型类(ActiveModel
),这些符号(更多其他)作为布尔属性。给定一个类实例,我想检索其值为true
的所有属性名。即:
# Given an array of symbols
[:attr_1, :attr_2, :attr_3]
# Given a class instance
<#Model attr_1: true, attr_2: false, attr_3: false, attr_4: true, ... attr_N: true>
# Then I would like to return
[:attr_1, :attr_4, ..., :attr_N]
我怎么做呢?
attrs = [:attr_1, :attr_2, :attr_3]
class Model
def are_true?(attr_names)
eval(attr_names.map {|a| "send(:#{a})"}.join(" && "))
end
def which_true?(attr_names)
attr_names.map {|a| a if send(a) == true}.compact
end
end
m = <#Model attr_1: true, attr_2: false, attr_3: false, attr_4: true, ... attr_N: true>
m.are_true?(attrs) # evals if all given attr_names are true
m.which_true?(attrs) # returns array of attr_names which are true
如果您有符号列表,您可以遍历它们并选择为真
symbols = [:attr_1, :attr_2, :attr_3]
symbols.select {|sym| object.send(sym) == true }
如果你没有你想要的符号列表,你可以简单地遍历模型的所有属性
symbols = object.attributes
symbols.select {|sym| object.send(sym) == true }