From: "David A. Black" Date: 2008-05-02T02:31:24+09:00 Subject: Re: splitting with a regex & keeping a ref? Hi -- On Fri, 2 May 2008, Kyle Schmitt wrote: > Robbert, yermej, David, > > Thanks a bunch! > Here's what I finally came up with, in case anyone's bored enough to wonder. > > file="/path/to/smb/file/sample.conf" > regex=/(\[[a-z0-9]+\])([^\[]*)/i > samba_config={} > File.open(file){|f| f.read()}.scan(regex) do > |title,options| > samba_config.store(title,{}) > options.strip.each() do > |l| > samba_config[title].store(l[/^[^=]*/].strip,l[/[^=]*[^\n]$/].strip) > end > end I know you're not asking for refactoring advice, but here's some anyway :-) If you're just going to read a file's contents into a string, you can use File.read, rather than the whole open/read thing. Also, I'd encourage you to drop the empty parentheses after method names. The message-sending dot tells you that it's a method; the () doesn't add signal, just noise. Anyway, here's a tweaked version, in case it's of interest. Nothing too radical, just a couple of possibly fun alternative techniques :-) File.read("filename").scan(regex) do |title,options| samba_config[title] = {} options.strip.each do |option| samba_config[title].update(Hash[*option.strip.split(/\s*=\s*/)]) end end David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!