2013-04-17 87 views
0

我正在解析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 

我應該如何得到paramscompany_name

回答

0

[["Company Name", "Field6"], ["Email", "Field5"]]是一種常見的數據模式,而且一旦你認識到它,你就會知道它很容易被裹挾到一個哈希:

hash = Hash[[["Company Name", "Field6"], ["Email", "Field5"]]] 

這裏是它看起來像現在:

 
{ 
    "Company Name" => "Field6", 
      "Email" => "Field5" 
} 

在那一點上,很容易得到VA攻略:

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,我不能肯定地說,但它可能已經是這種格式了,你正在做的事情是把它變成一個數組數組,這是一個哈希看起來像是如果運行通過mapcollect或者已經應用to_a

0

使用find method

fields_params.find{|x| x.first == "Company Name"}.last # => "Field6"