2013-06-12 27 views
0

我有一个这样的数组:嵌套一个给定的数组为儿童,根据病情

tweets = [ 
    { 
    :user_id => 234567, 
    :username => "A", 
    :created_at => "2012-10-12 10:20:30" 
    }, 
    { 
    :user_id => 234568, 
    :username => "B", 
    :created_at => "2012-10-12 10:20:34" 
    }, 
    { 
    :user_id => 234569, 
    :username => "C", 
    :created_at => "2012-10-12 10:20:35" 
    }, 
    { 
    :user_id => 234570, 
    :username => "D", 
    :created_at => "2012-10-12 10:20:40" 
    } 
] 

和另一个数组,像这样:

followers = [ 
    { 
    :user_id => 234567, 
    :follower_ids => [234568, 56654] 
    }, 
    { 
    :user_id => 234568, 
    :follower_ids => [234569, 454445] 
    }, 
    { 
    :user_id => 234569, 
    :follower_ids => [234570, 56333] 
    }, 
    { 
    :user_id => 234570, 
    :follower_ids => [45566, 61145] 
    } 
] 

我想窝成一个深层结构,其中一个被制造成另一个的孩子。为了使孩子们,要满足的条件是:

具有较大created_at比其他,和 包括在follower_ids名单在 该鸣叫的追随者阵列被认为是其user_id任何其他鸣叫要个孩子

,并给定数据预期输出是这样的:

arranged_tweets = [ 
    { 
    :user_id => 234567, 
    :username => "A", 
    :created_at => "2012-10-12 10:20:30", 
    :children => [ 
     { 
     :user_id => 234568, 
     :username => "B", 
     :created_at => "2012-10-12 10:20:34", 
     :children => [ 
      { 
      :user_id => 234569, 
      :username => "C", 
      :created_at => "2012-10-12 10:20:35", 
      :children => [ 
       { 
       :user_id => 234570, 
       :username => "D", 
       :created_at => "2012-10-12 10:20:40" 
       } 
      ] 
      } 
     ] 
     } 
    ] 
    } 
] 
+0

你是怎么做的而不写任何代码? –

+1

@ theTinMan ..你的意思是说,我试过的代码是什么? – rubyprince

回答

1

未经检验的,但守ld给你的想法:

arranged_tweets = tweets.collect do |tweet| 
    arranged_tweet(tweet, tweets - [tweet])   
end 

def arranged_tweet(tweet, other_tweets) 
    { :user_id => tweet[:user_id], ... 
    :children => children(tweet, other_tweets) } 
end 

def children(tweet, other_tweets) 
    other_tweets.find_all { |other| is_child?(other, tweet) }.collect do |other| 
    arranged_tweet(other, other_tweets - [other]) 
    end    
end 

def is_child?(tweet, parent_tweet) 
    parent_tweet[:created_at] > tweet[:created_at] && 
    is_follower?(tweet[:user_id], parent_tweet[:user_id])         
end 

def is_follower?(user_id, other_user_id) 
    followers[other_user_id][:follower_ids].include?(user_id) 
end 
+0

我试过了..但是没能弄清楚它..我最终自己做了这件事,想出了一个可能性很低的答案。 – rubyprince