data = [
{ name: :name, model: :Address, field_type: :string },
{ name: :country, model: :Address, field_type: :string },
{ name: :street , model: :Address, field_type: :string },
{ name: :city , model: :Address, field_type: :string },
{ name: :count , model: :Property, field_type: :integer },
{ name: :count2 , model: :Property, field_type: :integer } ,
{ name: :count3 , model: :Property, field_type: :integer } ,
{ name: :count3 , model: :Property, field_type: :integer }
]
我有一个哈希数组,我想查询哈希值。我想知道最有效,最推荐的解决方案。
例如,我可能需要找到所有哈希值的名称:integer。或者我可能想查询所有模型的名称:地址。或者我可能需要将所有field_types查询为唯一。
我可以直接查询哈希数组吗?如果可以的话,是否可以使用主动模型或其他方法更好?
答案 0 :(得分:3)
您有一系列“普通”的哈希。您可以使用Ruby方法:
data = [
{ name: :name, model: :Address, field_type: :string },
{ name: :country, model: :Address, field_type: :string },
{ name: :street, model: :Address, field_type: :string },
{ name: :city, model: :Address, field_type: :string },
{ name: :count, model: :Property, field_type: :integer },
{ name: :count2, model: :Property, field_type: :integer },
{ name: :count3, model: :Property, field_type: :integer },
{ name: :count3, model: :Property, field_type: :integer }
]
p data.select { |val| val[:field_type] == :integer }.map { |val| val[:name] }
# [:count, :count2, :count3, :count3]
p data.select { |val| val[:model] == :Address }.map { |val| val[:name] }
# [:name, :country, :street, :city]
p data.uniq { |val| val[:field_type] }
# [{:name=>:name, :model=>:Address, :field_type=>:string}, {:name=>:count, :model=>:Property, :field_type=>:integer}]