这个红宝石哈希有什么问题吗?

Dr.*_*ein 0 ruby hash

我对ruby很新,我不断收到以下错误:

in gem_original_require': ./helpers/navigation.rb:28: odd number list for Hash (SyntaxError)

任何帮助赞赏...

   module Sinatra::Navigation

        def navigation

            @navigation

                nav = {

                        primary[0] = {
                         :title => "cheddar",
                         :active => false,
                         :children => {
                           { :title => "cheese", :active => false },
                           { :title => "ham", :active => false }
                          }
                        },

                        primary[1] = {
                         :title => "gorgonzola",
                         :active => false,
                         :children => {
                           { :title => "What is the cheese?", :active => false },
                           { :title => "What cheese", :active => false },
                           { :title => "What does the cheese tell us?", :active => false, :children => {
                              { :title => "Cheessus", :active => false },
                              { :title => "The impact of different cheeses / characteristics for cheese in relation to CHSE outcomes", :active => false }
                            }
                           }
                          }
                        }
                }
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 6

在ruby中,花括号用于描述由键和值对组成的散列映射.方括号用于描述数组.您的children属性不包含键值对,因此您必须使用数组而不是哈希.

而不是

:children => {
  { :title => "cheese", :active => false },
  { :title => "ham", :active => false }
}
Run Code Online (Sandbox Code Playgroud)

做:

:children => [
  { :title => "cheese", :active => false },
  { :title => "ham", :active => false }
]
Run Code Online (Sandbox Code Playgroud)

对于其他事件也一样:children.

我也不确定primary[0] =应该达到什么目标,但它几乎肯定不会达到您想要的效果.它所做的是将assign设置为第一个元素primary(这意味着在该赋值之前必须存在一个名为primary的数组),然后返回该元素.

如果你想构建你的哈希以便可以访问它nav[:primary][0][:children][0],你必须这样做:

nav = {
  :primary => [
    {:title => "cheddar",
     :active => false,
     :children => [
                    { :title => "cheese", :active => false },
                    { :title => "ham", :active => false }
                  ]
    },
    {
       :title => "gorgonzola",
       #...
    }]
}
Run Code Online (Sandbox Code Playgroud)

另请注意,@navigation分配之前的行nav根本不执行任何操作.