0

我有以下内容:

BB_AREAS = {
  :about          => {:link => "quem somos", :slug => "quem-somos"},
  :expositors     => {:link => "expositores",:slug => "expositores"},
  :map            => {:link => "planta", :slug => "planta"},
  :activities     => {:link => "atividades",:slug => "atividades"},
  :address        => {:link => "como chegar",:slug => "como-chegar"},
  :support        => {:link => "apoio", :slug => "apoio"},
  :optin          => {:link => "cadastro",:slug => "cadastro"},
  :how_expositors => {:link => "como expor",:slug => "como-expor"},
  :press          => {:link => "imprensa",:slug => "imprensa"},
  :contact        => {:link => "contato",:slug => "contato"},
}

BB_MENU_AREAS       = BB_AREAS.each_with_object({}) { |(k, v), h| h[k] = v[:link]}
BB_MENU_AREAS_SLUG  = BB_AREAS.each_with_object({}) { |(k, v), h| h[k] = v[:slug]}

在我看来,我有以下几点:

=render :partial => '/shared/menu', :collection => BB_MENU_AREAS.map {|link, menu| {:link => link, :menu => menu}}, :spacer_template => '/shared/menu_separator'

我希望菜单以与 BB_AREAS 相同的顺序呈现,但它以任意顺序呈现。

4

2 回答 2

3

在 Ruby 1.9+ 中,哈希是按插入顺序排序的,否则它们有一个内部顺序。

不过,IMO 此数据属于实际对象数组;大致:

class Area
  attr_accessor :name, :link, :slug
  def initialize(name, link, slug)
    @name = name
    @link = link
    @slug = slig
  end
end

BB_AREAS = [
  Area.new("About", "quem somos", "quem-somos"),
  Area.new("Expositors", "expositores", "expositores"),
  # etc.
]

如果您确实需要按顺序提取单个组件。

于 2013-03-05T14:31:34.343 回答
0

Ruby 哈希在 Ruby 1.8 及更低版本中是无序的。但是,在 Ruby 1.9 及更高版本中,哈希是有序的。但是有一个向后兼容的解决方案:

BB_AREAS = [
  [:about          , {:link => "quem somos", :slug => "quem-somos"}],
  [:expositors     , {:link => "expositores",:slug => "expositores"}],
  [:map            , {:link => "planta", :slug => "planta"}],
  [:activities     , {:link => "atividades",:slug => "atividades"}],
  [:address        , {:link => "como chegar",:slug => "como-chegar"}],
  [:support        , {:link => "apoio", :slug => "apoio"}],
  [:optin          , {:link => "cadastro",:slug => "cadastro"}],
  [:how_expositors , {:link => "como expor",:slug => "como-expor"}],
  [:press          , {:link => "imprensa",:slug => "imprensa"}],
  [:contact        , {:link => "contato",:slug => "contato"}],
]
BB_MENU_AREAS       = BB_AREAS.each_with_object({}) { |(k, v), h| h[k] = v[:link]}
BB_MENU_AREAS_SLUG  = BB_AREAS.each_with_object({}) { |(k, v), h| h[k] = v[:slug]}

你的观点没有任何改变。此外,在此数据结构中[key],您需要使用.assoc(key)[1].

于 2013-03-05T14:29:14.400 回答