data sctructure

  • Thread starter Juliano 준호
  • Start date
J

Juliano 준호

Hello guys.

I've just started using ruby and I come from Python... I'm still
learning to think the Ruby way...
Of course, any beginning is hard, but even so I've been having a lot
of fun learning Ruby.
The problem is that I still don't know much about the tons of methods
and I'm maybe letting something pass through my fingers.

My problem is this:
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:

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] = {}
end
if !d[c].has_key? fc
d[c][fc] = []
end
d[c][fc].push fl
end
return d
end

My question is: Is there an easier way to do this in Ruby as it is in
Python?

Same code in Python...

def preprocess(lines):
d = {}
for line in lines:
c, s, fc, fl = line
dc = d.setdefault(c, {})
ds = dc.setdefault(s, {})
dfc = ds.setdefault(fc, [])
lfl = dfc.append(fl)
return d

Thank you very much! :)
 
R

Robert Klemme

2009/8/28 David A. Black said:
This message is in MIME format. The first part should be readable text,
while the remaining parts are likely unreadable without MIME-aware tools=
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top