Galet
Galet

Reputation: 6269

How to create dynamic array of hashes in Ruby on rails

I am doing POST request to the endpoint using HTTparty gem in Ruby on Rails application.

I am passing request body as json in the POST request.

request_body = {}
request_body[:name] = "John"
request_body[:age] = 26
request_body[:revenue] = [{id: "price"}, {id: "tax"}}]
request_body[:contact] = [{id: "email"}, {id: "phone"}}]

I am creating the above request body structure for multiple request. How can I form the request body in a better way?

Is there a way to create array of hashes by passing only the values(e.g. price and tax) instead of using like below

request_body[:revenue] = [{id: "price"}, {id: "tax"}}]

Below is my scenario, I want to pass the values of hashes and method will return array of hashes.

Input:

attributes = %w(price tax)

array_of_hashes(attributes)

Expected output:

def array_of_hashes()
 [{id: "price"}, {id: "tax"}}]
end

Upvotes: 0

Views: 659

Answers (1)

Sumanth Madishetty
Sumanth Madishetty

Reputation: 3605

You can try this

def array_of_hashes array
   array.map{ |el| {id: el} }
end

and

array_of_hashes(["price", "tax"]) -> returns [{ id: "price" }, {id: "tax"}]

Upvotes: 1

Related Questions