2010-02-10 31 views
2

我無法使用國家/地區代碼:{「AF」=>「阿富汗」,「AL」=>「阿爾巴尼亞」,「DZ」)在國家名稱的哈希數據結構中呈現ruby中的json響應。 =>「阿爾及利亞」,...},以便json響應按照字母順序排列如下:我怎樣才能渲染一個哈希json響應,同時維護軌道上的紅寶石順序?

{「AF」:「Afghanistan」,「AL」:「Albania」,「DZ」=> 「Algeria」...}

這個問題,我的理解是,一個紅寶石散列本身沒有秩序的概念。所以反應是完全隨機的。

感謝您的任何幫助!

馬丁

+0

Ruby 1.9已經訂購了哈希。 – guns 2010-02-10 04:44:57

回答

0

如何散列像一個數組:

[{ "AF"=>"Afghanistan"}, {"AL"=>"Albania"}, {"DZ"=>"Algeria"}, ... ] 
+0

如果HTTP響應需要使用特定的格式,這將不起作用。 – 2010-02-10 03:15:43

4

您可以使用ActiveSupport::OrderedHash

樣本案例:

hash = ActiveSupport::OrderedHash.new 
hash["one"] = "one" 
hash["two"] = "two" 
hash["three"] = "three" 
p hash   # Will give you the hash in reverse order 
p hash.to_json # Will give you a json with the ordered hash 
+0

嗨westoque!這正是我正在尋找的。 – mtin79 2010-02-10 04:33:08

0

得益於以前的答案( - > westoque )我結束了猴子修補程序的哈希類的軌道初始化文件夾像臨屋區t:

class Hash 
def to_inverted_ordered_hash 
    copy = self.dup.invert.sort 
    copy.inject(ActiveSupport::OrderedHash.new) {|hash, i| hash[i[1]] = i[0]; hash} 
end 

def to_ordered_hash 
    copy = self.dup.sort 
    copy.inject(ActiveSupport::OrderedHash.new) {|hash, i| hash[i[1]] = i[0]; hash} 
end 
end 

並且當從控制器呈現時調用to_json。 非常感謝!

相關問題