开发者

Can somenone translate this from Ruby to Python. Its a basic map function [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

This function is from the mongodb site: http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails

def self.threaded_with_field(story, field_name='votes')
    comments = find(:all, :conditions => {:story_id => story.id}, :order => "path asc,  #{field_name} desc")
    results, map = [], {}
    comments.each do |comment|
      if comment.parent_id.blank?
        results << comment
      else
        comment.path =~ /:([\d|\w]+)$/
        if parent = $1
          map[parent] ||= []
          map[parent] << comment
        end
      end
    end
    assemble(results, map)
  end

Its just the use of array and hashes that tripped me up. Characters like ||,<<, and this string "||=[]". I understand active record and the rest of the function. Otherwise I will just read the first 60 or so pages of an into to Ruby Book, which I was not dying to do开发者_StackOverflow.


So to answer your questions regarding operators like << or ||= []:

  • << appends an element to an array (or appends strings), in the case above it's used to append the comment object to either the results array or or the threaded thingy.
  • ||= basically means, if left-hand-side is undefined then evaluate & assign right-hand-side ([] is the same as Array.new) => "if map[parent] is undefined, initialize it with Array.new - else do nothing"

To method above creates an array with parent comments (results) and a hash with child comments (map).


This method can't be translated directly. It relies on several framework methods that would exist only in an ActiveRecord or Mongoid::Document class (e.g. Model#find) -- unless you're using an identical framework in Python, you would also have to implement these methods yourself.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜