From: Raf Coremans Date: 2007-05-10T06:38:12+09:00 Subject: Re: What's the most ruby-ish way to write this python code? 2007/5/9, Drew Olson : > All - > > I've been using ruby for quite some time and I'm only beginning to look > at python. I really like the way ruby flows as compared to python and I > can't see myself getting pulled away from ruby. However, there is one > thing I like about python, and that is the generators. What is the best > way to translate the following code into ruby? Assume word is some > string and letters is a string of all the characters a..z: > > [word[0:i]+c+word[i+1:] for i in range(len(word)) for c in letters] > > This is all based on trying to efficiently rewrite > http://norvig.com/spell-correct.html in ruby. Essentially what this code > does is get the array of words resulting from inserting every character > at every possible position in the given word. I find it pretty succinct, > but I know ruby can do better! I've come up with two ways to do this in > ruby, but neither seems to "click" with me: > > (0...word.size).inject([]) do |words,i| > letters.split('').each do |c| > words << word[0...i]+c+word[i..-1] > end > words > end > > OR > > (0...words.size).map do |i| > letters.split('').map do |c| > word[0...i]+c+word[i..-1] > end > end.flatten > > Any advice? Currenty, I'm using the first approach and it's sloooooow > (I'm assuming inject has high overhead). > > -- > Posted via http://www.ruby-forum.com/. > > Both ways seem ruby-esque to me. Note though that you should use word[i+1..-1] (not word[i..-1]) in order to get the same result as your python code. The fastest executing algorithm that I could find was: ar = [] (0...word.size).each do |i| letters.split(//).each do |c| ar << word.dup ar[-1][i] = c end end Regards, Raf