0

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
4
  • can you post an example of your requirement, do you want to create an array of hashes wih the keys you specify Commented Jul 12, 2019 at 9:22
  • @SumanthMadishetty Refer my update. I want to form the array of hashes in a dynamic way Commented Jul 12, 2019 at 9:26
  • From what input? Commented Jul 12, 2019 at 9:38
  • @NickM Refer my question. I have already updated it Commented Jul 12, 2019 at 9:41

1 Answer 1

1

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"}]
Sign up to request clarification or add additional context in comments.

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.