Posts Tagged: ruby


19
Jan 11

Using regular expressions? The Devil is in the details.

Recently, I ran into a little roadblock as I’ve been cleaning up some bugs for one of my applications. I rely heavily on cross pollination of data between sites to drive traffic across my network. In this particular situation, a simple collection of linked image thumbnails accomplishes this task.

One of the helper methods that I use returns the file name of a supplied post object. To do this, I perform a regular expression match against the post’s URL and return the result.

# post.url(:icon) = id/10/icon/foo.jpg
# returns "icon/foo.jpg"

def filename_from_post(post)
  return post.image.url(:icon).match(/icon\/.*\.jpg)/)[0]
end

That worked great until my application would randomly throw a NoMethodError. I spent a while scratching my head, looking over my code, checking my SQL queries, and so on and so forth. Finally, I figured it out…I had forgotten to specify a case insensitive search!

# post.url(:icon) = id/10/icon/bar.JPG
# returns nil

>> post.url(:icon).match(/icon\/.*\.jpg/)
=> nil

>> post.url(:icon).match(/icon\/.*\.jpg/i)
=> #<MatchData "icon/bar.JPG">

I guess what they say is true…the Devil is in the details.


20
Feb 08

Raise a value to a negative power in Ruby

I ran into a few kinks trying to raise some numbers to a negative power in Ruby. Ruby uses the ** operator for exponential calculations. Here’s the little hiccup I encountered:

# 2^2 = 4
# here is the IRB dump
>> 2**-2
=> Rational(1, 4)

# but I don't want the actual number!
>> (2**-2).to_f
=> 0.25