0

我正在使用 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]

我怎样才能做到这一点?

4

2 回答 2

1
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
于 2012-12-22T15:05:13.533 回答
0

如果您有符号列表,则可以遍历它们并选择正确的符号

symbols = [:attr_1, :attr_2, :attr_3]
symbols.select {|sym| object.send(sym) == true }

如果您没有所需的符号列表,则可以简单地遍历模型的所有属性

symbols = object.attributes
symbols.select {|sym| object.send(sym) == true }
于 2012-12-22T12:29:52.747 回答