I want to iterate over this data to extract the value of the ids:
[ {:id => 3, :quantity => 5 }, { :id => 4, :quantity => 3 } ]
I want to iterate over this data to extract the value of the ids:
[ {:id => 3, :quantity => 5 }, { :id => 4, :quantity => 3 } ]
You can use Array's map
method like below:
arr =[ {:id => 3, :quantity => 5 }, { :id => 4, :quantity => 3 } ]
ids = arr.map { |k| k[:id] }
#=> [3,4]
[ {:id => 3, :quantity => 5 }, { :id => 4, :quantity => 3 } ].each do |hash|
puts hash[:id]
end
This will puts
each id value on the screen. You can do what you need to do from there.
There's more than one way to do this in Ruby. A lot depends on what you're trying to express. If you're not trying to play code golf, one way to do this is with Hash#values_at. For example:
[{id: 3, quantity: 5}, {id: 4, quantity: 3}].flat_map { |h| h.values_at :id }
#=> [3, 4]
A more Rails-like way would be to just ActiveRecord::Calculations#pluck the attributes you want in the query itself. For example:
Stuff.where(quantity: [3, 5]).pluck :id
There are certainly other ways to get the same result. Your mileage may vary, depending on your real use case.