Sunday, March 15, 2009

Variation on index method from Class String

Ok, so I wanted to find the indices of all occurrences of String 'A' within a larger String 'B'. The Ruby core String class's index and rindex methods do this for one value, but not for all of them.

A recursive solution made the most sense (note: ternary operator has to be on one line):
def indices(str, pos = 0)
!self.index(str, pos).nil? /
? (self.indices(str, self.index(str, pos) + 1) /
| [].push(self.index(str, pos))).sort : []
end
That gives an array of all of the indices in sorted order, and is actually quite cryptic. Here's a more readable version:
def indices(str, pos = 0)
if (!self.index(str, pos).nil?)
# Get the position of the current find
x = self.index(str, pos)
# Return the union of what you found
# and look for more occurrences
[].push(x) | self.indices(str, x + 1)
else
# Basecase. Return empty array for union "|"
[]
end
end

Sunday, March 1, 2009

Heroku gem deployment last resort

If you're having problems installing a gem in your heroku app, check this out as a last resort:

Here's the workaround (commands in bold):
1.) Get a local copy of your app by using the export option on heroku.
2.) Unpack it to a local folder and open up a command line/shell/command prompt.
3.) cd to your app's directory
4.) gem install gemsonrails to get gemsonrails installed to your local gem repo
5.) gemsonrails to install some gemsonrails helpers to your app's environment
5.) rake gems:install GEM=gem_you_want -> gets your gem from the gem cloud in the sky and places it in vendor/gems
6.) rake gems:freeze GEM=gem_you_want -> gets your gem ready for primetime
7.) tar czf myapp.tar.gz myapp/
8.) upload the tar.gz to heroku
9.) sigh with relief because you can now use your favorite gem.