根据条件将给定数组嵌套到子项中

时间:2013-06-12 06:49:05

标签: ruby ruby-on-rails-3

我有一个这样的数组:

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的推文   其中user_id包含在follower_ids列表中,如果该推文在   追随者阵列被认为是一个孩子

并且给定数据的预期输出如下:

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"
              }
            ]
          }
        ]
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:1)

未经测试,但应该给你一个想法:

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