From: voipfc@... Date: 2006-10-12T03:55:11+09:00 Subject: Re: Ruby's equivalent of PHP explode I wrote my first ruby program and displayed it here - http://groups.google.co.uk/group/comp.lang.ruby/browse_frm/thread/d9a5608bdfb5ebbd/dfe7da9069b5bf40?lnk=st&q=voipfc&rnum=1&hl=en#dfe7da9069b5bf40 When I apply some text to it I receive this error message ======= templatefiller.rb:33:in `fetch': key not found (IndexError) from templatefiller.rb:33:in `run' from templatefiller.rb:32:in `run' from templatefiller.rb:31:in `run' from templatefiller.rb:126 from c:/webdirectory/ruby/lib/ruby/1.8/find.rb:39:in `find' from c:/webdirectory/ruby/lib/ruby/1.8/find.rb:38:in `find' from templatefiller.rb:110 from templatefiller.rb:109 Could anyone explain what is happening? Mike Dvorkin wrote: > Actually the split method has second parameter where you can specify > number of splits you want, i.e.: > > data.each do |line| > key, value = line.split(/=/, 2) > end > > HTH. > Mike Dvorkin > http://www.rubywizards.com > > > On Sep 26, 2006, at 1:35 PM, voipfc@googlemail.com wrote: > > > > > Paul Lutus wrote: > >> voipfc@googlemail.com wrote: > >> > >>> > >>> What is ruby's equivalent of PHPs explode? > >>> > >>> A routine which can breakdown a string and return the results in an > >>> array or a routine that can parse an .ini file and return the key > >>> value pairs in an array[key]=value. > >> > >> Actually, that is two questions. As to the first (explode a string > >> on word > >> boundaries), you've been given an answer: > >> > >> array = string.split("\s") # many variations > >> > >> As to the second, read an .ini file and break it down by line and by > >> name/value pairs (not tested): > >> > >> data = File.read("filename.ini") > >> > >> my_hash = {} > >> > >> data.each do |line| > >> key,value = line.split("=") > >> my_hash[key] = value > >> end > >> > >> The second won't work properly if there are any equals signs in > >> the value > >> field. The solution for this is only a bit more complex. > >> > > > > Will this fix the multiple = sign problem > > > > data.each do |line| > > my_hash[line.slice[0, line.index("=") - 1] = > > line.slice[line.index("="), line.length -line.index("=")] > > end > > > > I am new to Ruby and rightly or wrongly it looks rather unRuby like, > > can it be expressed more elegantly? > > > > > >> -- > >> Paul Lutus > >> http://www.arachnoid.com > > > >