0
Array = [{:acronym => "AC", :fullname => "Acre"}, {:acronym => "AL", :fullname => "Alagoas"}, {:acronym => "AP", :fullname => "Amapá"}, {:acronym => "AM", :fullname => "Amazonas"}, {:acronym => "BA", :fullname => "Bahia"}, {:acronym => "CE", :fullname => "Ceará"}, {:acronym => "DF", :fullname => "Distrito Federal"}, {:acronym => "ES", :fullname => "Espírito Santo"}, {:acronym => "GO", :fullname => "Goiás"}, {:acronym => "MA", :fullname => "Maranhão"}, {:acronym => "MT", :fullname => "Mato Grosso"}, {:acronym => "MS", :fullname => "Mato Grosso do Sul"}, {:acronym => "MG", :fullname => "Minas Gerais"}, {:acronym => "PA", :fullname => "Pará"}, {:acronym => "PB", :fullname => "Paraíba"}, {:acronym => "PR", :fullname => "Paraná"}, {:acronym => "PE", :fullname => "Pernambuco"}, {:acronym => "PI", :fullname => "Piauí"}, {:acronym => "RR", :fullname => "Roraima"}, {:acronym => "RO", :fullname => "Rondônia"}, {:acronym => "RJ", :fullname => "Rio de Janeiro"}, {:acronym => "RN", :fullname => "Rio Grande do Norte"}, {:acronym => "RS", :fullname => "Rio Grande do Sul"}, {:acronym => "SC", :fullname => "Santa Catarina"}, {:acronym => "SP", :fullname => "São Paulo"}, {:acronym => "SE", :fullname => "Sergipe"}, {:acronym => "TO", :fullname => "Tocantins"}]

如何将变量与其他变量进行比较:acronym并返回:fullname?我正在尝试使用 Rails 助手来做到这一点。

4

2 回答 2

2

首先,你不想调用你的数组Array,因为这是一个类名,它已经被占用了。

你可以这样做:

def find_acronym_in(array, acronym)
    # returns nil if we don't find a match.
    array.find { |h| h[:acronym] == acronym }.try(:fetch, :fullname)
end

在你的 ERB 中:

<%= find_acronym_in(@acronyms, 'ES') %>

这是一个简单的线性搜索,因此对于大型列表来说会很慢,但对于短列表来说可能不会很明显。

如果你做了很多这样的事情,或者如果你有很大的列表,那么你可以在你的控制器中将你的数组重新排列成一个简单的哈希:

@acronyms_hash = @acronyms.each_with_object({ }) { |h, memo| memo[h[:acronym]] = h[:fullname] }

然后根据需要从哈希中提取内容:

<%= @acronyms_hash['ES'] %>
于 2011-10-04T01:41:31.417 回答
1

这会做到的

acronym_to_find = "SE"
Array.select { |ac| ac[:acronym] == acronym_to_find }.first[:fullname]

不过,您的数据可能会更好地结构化为 { acronym => fullname} 对的哈希。

于 2011-10-04T01:38:11.243 回答