0

I have following array of hash. I am trying to loop over it and build an array of hash of values of id and product_order_id.

objects = 
[
  #<Product: 0x00007ffd4a561108
  @id="1",
  @product_id="2",
  @product_order_id="23",
  @description="abc",
  @status="abcde",
  @start_date=nil,
  @end_date=nil>,
  #<Product: 0x00007ffd4a560c80
  @id="45",
  @product_id="22",
  @product_order_id="87",
  @description="ahef",
  @status="gesff",
  @start_date=nil,
  @end_date=nil>
......more objects.....
    ]

This is what it should look like

[{ "1": "23" }, { "45": "87" }] -->its going to be uuid

I tried doing this but no luck

def mapped_product(objects)
    mapping = []
    objects.each do |object|
      mapping << {
        object.product_order_id: object.id
      }
    end
end

Any idea?

4
  • Don't you mean it should look like [{ 1=>23 }, { 45=>87 }], as symbol names cannot begin with a digit? Commented Dec 4, 2018 at 3:49
  • What you expect is invalid. Commented Dec 4, 2018 at 4:27
  • A quick question, why do you want an array containing hashes that have only one key/value pair? It seems to me that { '1' => '23', '45' => '87' } (one hash without wrapped array) is a better result. Commented Dec 4, 2018 at 15:43
  • The array of hash is not going to be just have 2 values, it could have 100 or 500 objects Commented Dec 4, 2018 at 15:56

3 Answers 3

1

inline solution:

> Hash[objects.map{|p| [p.id, p.product_order_id] }]
# Output : [{ 1=>23 }, { 45=>87 }]
Sign up to request clarification or add additional context in comments.

Comments

1

I'd usually implement it using an each_with_object

objects.each_with_object({}) { |obj, acc| acc[obj.id] = obj.product_order_id }

Unless I reaaaly want to squeeze some performance, than I'd go with Gagan's answer

Comments

0

Have you tried this?

def mapped_product(objects)
    mapping = []
    objects.each do |object|
      mapping << {
        object.id => object.product_order_id # I'm using an `=>` here
      }
    end
    mapping # return the new mapping
end

I've just changed the : on the hash for a => to "make it dynamic" and swapped the values of id and product_order_id

You can also use a map here:

def mapped_product(objects)
    objects.map do |object|
     {  object.id => object.product_order_id }
    end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.