[英]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. 我在Ruby on Rails应用程序中使用HTTparty gem向端点执行POST请求。
I am passing request body as json in the POST request. 我在POST请求中将请求正文作为json传递。
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(eg 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
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"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.