![](/img/trans.png)
[英]How to create an array of hashes by mapping 2 hashes in ruby on rails
[英]How to create dynamic array of hashes in Ruby on rails
我在Ruby on Rails应用程序中使用HTTparty gem向端点执行POST请求。
我在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"}}]
我正在为多个请求创建以上请求正文结构。 如何更好地形成请求正文?
有没有一种方法可以通过仅传递值(例如价格和税)来创建哈希数组,而不是像下面这样使用
request_body[:revenue] = [{id: "price"}, {id: "tax"}}]
下面是我的情况,我想传递哈希值,方法将返回哈希数组。
输入 :
attributes = %w(price tax)
array_of_hashes(attributes)
预期产量:
def array_of_hashes()
[{id: "price"}, {id: "tax"}}]
end
你可以试试这个
def array_of_hashes array
array.map{ |el| {id: el} }
end
和
array_of_hashes(["price", "tax"]) -> returns [{ id: "price" }, {id: "tax"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.