user2012677
user2012677

Reputation: 5735

Query an array of hashes (Rails 5.2)

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 }
      ]

I have an array of hashes and I would like to query the hash values. I would like to know the most efficient and most recommended solution.

For example, I may need to find all the names of the hashes that are :integer. OR I may want to query all the names of the models that are :Address. OR I may need to query all the field_types as unique.

Can I query the array of hashes directly? if so how, and if not, is there a better method using active model or something?

Upvotes: 2

Views: 413

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

You have a "plain" array of hashes. You can use Ruby methods:

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}]

Upvotes: 4

Related Questions