Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
Re: What's the most ruby-ish way to write this python code?
Kim Metsgar
5/12/2007 10:53:00 PM
Does anybody know how to unsubscribe from this ... too many messages
-----Original Message-----
From: list-bounce@example.com [mailto:list-bounce@example.com] On Behalf Of
Drew Olson
Sent: Wednesday, May 09, 2007 2:02 PM
To: ruby-talk ML
Subject: What's the most ruby-ish way to write this python code?
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-co...
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-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Re: What's the most ruby-ish way to write this python code?
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password