我正在解析JSON并将其作为fields_array
传递给呈现erb
模板。这是一个Sinatra应用程序。
我有:
private
def fields_params
# example of parsed JSON, Company Name sometimes is Field6 but sometimes Field3
[["Company Name", "Field6"], ["Email", "Field5"]]
end
def company_name
# I want to return company name from params[company_field_id]
# Maybe something like:
id = fields_params.select{|field| field[0] == "Company Name" }.flatten[1]
params[id]
end
def fields_array
fields_params.collect do |label, param_id|
{ label: label, value: params[param_id] } if params[param_id]
end
end
我应该如何从company_name
获取params
?
答案 0 :(得分:0)
fields_params.find{|x| x.first == "Company Name"}.last # => "Field6"
答案 1 :(得分:0)
[["Company Name", "Field6"], ["Email", "Field5"]]
是一种常见的数据模式,一旦你认识到它,你就会知道它很容易被强制转化为哈希:
hash = Hash[[["Company Name", "Field6"], ["Email", "Field5"]]]
现在看来是这样的:
{ "Company Name" => "Field6", "Email" => "Field5" }
此时,很容易获得价值:
hash['Company Name']
=> "Field6"
因此,我会修改您的代码以返回哈希值,从而使检索值变得更加容易:
def fields_params # example of parsed JSON, Company Name sometimes is Field6 but sometimes Field3 Hash[ [["Company Name", "Field6"], ["Email", "Field5"]] ] end
很多时候我看到的JSON在解析后已经会产生某种哈希值。没有看到你的输入JSON我不能肯定地说,但它可能已经是那种格式,而你正在做的事情就是把它变成一个数组数组,如果运行{{1或} map
或已应用collect
。