From: "David A. Black" Date: 2009-09-17T03:30:59+09:00 Subject: Re: string to array Hi -- On Thu, 17 Sep 2009, John W Higgins wrote: > On Wed, Sep 16, 2009 at 10:50 AM, Re BR wrote: > >> John W Higgins wrote: >>> On Wed, Sep 16, 2009 at 9:20 AM, John W Higgins >>> wrote: >>> >>>>> >>>> x = "apple-orange-grape" >>>> tmp = x.split('-') >>>> (0..tmp.length-1).map{ |i| e[i..-1].join('-') } >>>> >>> >>> Sorry that should be >>> >>> (0..tmp.length-1).map{ |i| tmp[i..-1].join('-') } >>> >>> John >> >> trying to make this as a one liner >> >> a.split('.').map{ |i| a[i..-1].join('.') } >> >> but I am missing something >> > > There are two problems here. First, the a[i..-1] concept needs the array > from a.split('.') to work and therefore you need to store it. Also, the map > doesn't give you the indexes which is what the i is here. The a[i..-1] works > by creating an array of each element till the end so you want the index > which is not what the .map in this case will give you. > > I'm not sure there is a one liner method going down this road. Maybe the > regex options would work that way but not the split and rejoin concept (at > least I couldn't get it there). Well, hardly worth the trouble, but: str.split('-').inject([]){|acc,s|acc<<[acc[-1],s].compact.join('-')}.reverse :-) David -- David A. Black, Director Ruby Power and Light, LLC (http://www.rubypal.com) Ruby/Rails training, consulting, mentoring, code review Book: The Well-Grounded Rubyist (http://www.manning.com/black2)