Can somenone translate this from Ruby to Python. Its a basic map function [closed]
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 thecomment
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 asArray.new
) => "ifmap[parent]
is undefined, initialize it withArray.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.
精彩评论