Home > database >  Ruby change key value of hash
Ruby change key value of hash

Time:10-21

I have a query that returns this array and hash. How can I change the hash and add new key value pair to it import_id: 1, cost: 0 or can I do a map on the query?

The query

name = Store.joins(:paid => :supply).group(:name).select("supply.name").where("stores.identifier IN (?) ", tids).pluck(:supply_id, :name)

array

[[258, "Square"], [245, "App"]]

when I convert it to hash it returns

{258=>"Square", 245=>"App"}

desired output

{{supply_id: 258, name: "Square", import_id: 1, cost: 0}, {supply_id: 245, name: "App", import_id: 1, cost: 0}}

CodePudding user response:

It appears the response is an array of [supply_id, name] pairs. You can easily destructure the array and restructure the data as hashes with proper symbolic keys.

array = [[258, "Square"], [245, "App"]]

array.map do |(id, name)|
  { supply_id: id, name: name, import_id: 1, cost: 0 }
end

# [{:supply_id=>258, :name=>"Square", :import_id=>1, :cost=>0}, ...]

CodePudding user response:

Use #select instead of #pluck and call .as_json or .map(&:attributes)

Store.joins(:paid => :supply).group(:name)
  .select("supply.name").where("stores.identifier IN (?) ", tids)
  .select(:supply_id, :name).as_json

# [{supply_id: 258, name: "Square"}, {supply_id: 245, name: "App"}]

or

Store.joins(:paid => :supply).group(:name)
  .select("supply.name").where("stores.identifier IN (?) ", tids)
  .select(:supply_id, :name).map(&:attributes)

# [{supply_id: 258, name: "Square"}, {supply_id: 245, name: "App"}]

or you can construct Hash with {import_id: 1, cost: 0} appended

Store.joins(:paid => :supply).group(:name)
  .select("supply.name").where("stores.identifier IN (?) ", tids)
  .select(:supply_id, :name)
  .map {|e| {supply_id: e.supply_id, name: e.name, import_id: 1, cost: 0} }

# [{supply_id: 258, name: "Square", import_id: 1, cost: 0}, {supply_id: 245, name: "App", import_id: 1, cost: 0}]

or

You can use Hash#merge during Hash generation step to include {import_id: 1, cost: 0}

hash.merge({import_id: 1, cost: 0})

# To achieve: {{supply_id: 258, name: "Square", import_id: 1, cost: 0}, {supply_id: 245, name: "App", import_id: 1, cost: 0}}
  • Related