如何在Ruby on Rails中创建哈希的动态数组

时间:2019-07-12 09:01:07

标签: ruby-on-rails arrays ruby hash

我正在使用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

1 个答案:

答案 0 :(得分:1)

您可以尝试

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

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