From: William James Date: 2009-02-12T10:18:48+09:00 Subject: Re: Method to get string combinations Christoph Blank wrote: > Hi, > > I have a text like this: > > "This {is|was} a {good|nice} day" and want to generate possible > combinations like: > > This is a good day > This was a good day > This is a nice day > This was a nice day > > I tried using zsh functionality to output this, but it doesn't seem > that easy. > Does anyone know an easy way how to do this in ruby? > > Thank you. def comb ary ary.inject([[]]){|old,lst| lst.inject([]){|new,e| new + old.map{|c| c + [ e ] }}} end s = "This {is|was|will be} a {good|nice} day to {surf|swim}." f = nil a,b = s.split( /\{(.*?)\}/ ).partition{f=!f} a = a.join( "%s" ) + "\n" b.map!{|s| s.split "|"} comb(b).each{|x| printf a % x } --- output --- This is a good day to surf. This was a good day to surf. This will be a good day to surf. This is a nice day to surf. This was a nice day to surf. This will be a nice day to surf. This is a good day to swim. This was a good day to swim. This will be a good day to swim. This is a nice day to swim. This was a nice day to swim. This will be a nice day to swim.