我正在使用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
答案 0 :(得分:1)
您可以尝试
def array_of_hashes array
array.map{ |el| {id: el} }
end
和
array_of_hashes(["price", "tax"]) -> returns [{ id: "price" }, {id: "tax"}]