From: Glenn Jackman Date: 2009-08-28T20:20:06+09:00 Subject: Re: data sctructure At 2009-08-28 06:16AM, "Juliano ??" wrote: > I have to read a file and set up a data structure of embedded > dictionaries. In Python I can easily do that by means of > "dict.defaultdict()", but I didn't understand how to do that in > Ruby... I finally came up with the following: Referencing a hash element that doesn't exist returns nil, so you might be looking for the ||= operator: a ||= b # if a is false or nil, then set a=b, else return value of a > def preprocess(lines) > d = {} > lines.each do |line| > c, s, fc, fl = line.split("\t") > if !d.has_key? c > d[c] = {} > end > if !d[c].has_key? s > d[c][s] = {} > end > if !d[c][s].has_key? fc > d[c][s][fc] = [] > end > d[c][s][fc].push fl > end > return d > end def preprocess(lines) d = {} lines.each do |line| c,s,fc,fl = line.split("\t") d[c] ||= {} d[c][s] ||= {} d[c][s][fc] ||= [] d[c][s][fc] << fl end d end -- Glenn Jackman Write a wise saying and your name will live forever. -- Anonymous