开发者

Ruby on Rails: I'm trying to recursively generate a hash, but I get {...} where there is supposed to be another depth of data

This is what I've been getting:

{:user=>{:employees=>{...}, :login=>"dernalia", :id=>1, :role=>2}}

What is generating the hash:

  def management_tree(args = {})
    args = {:users => [], :result => {}}.merge(args) #defaults
    result = args[:result]

    if not args[:users].include? self.login #prevent duplicates
      result.merge!({:user => {:id => self.id, 
                              :login => self.login,
                              :role => self.role,
                              :employees => employee_tree(args[:users] + [self.login], args[:result])
                              }
                    })      

    end
    logger.info result.inspect
    return result
  end

  def employee_tree(users, result)
    if self.employees.length > 0
       self.employees.each {|emp| (emp.management_tree({:users => users, :result => result})) }
    end
    return result
  end

Now... it's supposed to return something like this:

{:user=>{:login=>"me", :id=>1, :role=>2, 
        :employees=>{
             :user => {:login => "2", ...},
             :user => {:login => "3",
                   :employees => {...}
         }

}}

Some console output:

% bundle exec script/console
Loading development environment (Rails 2.3.8)
>> require "awesome_print"
=> []
>> ap User.find(1).management_tree[:employees]
nil
=> nil
>> ap User.find(1).management_tree
{
    :user => {
        :employees => {...},
             :role => 2,
  开发者_如何学JAVA          :login => "me",
               :id => 1
    }
}
=> {:user=>{:employees=>{...}, :role=>2, :login=>"me", :id=>1}}
>> 

now... it says that employees is nil... but it shouldn't be... it should have 3 hashes ... =\

but also, what does {...} mean? it seams terribly ambiguous


Ruby is clever about recursive structures and will use "..." instead of looping indefinitely.

For example:

a = [1, 2]
a << a # a is now recursive, since it contains itself
a.to_s # => [1, 2, [...]]
a[2][2][2][2][2][2][2] == a # => true

In your case, the {...} refers to any of the hashes already in the process of being outputed.

Maybe what you meant to do was to insert a copy of a hash? In the simple array example:

a = [1, 2]
a << a.dup # a is not recursive
a.to_s # => [1, 2, [1, 2]]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜