Ruby Tips

An on going list of simple tips and info.

return is slower than implicit return

require 'benchmark'

def ret(x); return x+1 end
def nret(x); x+1; end

n = 50000
Benchmark.bm do |b|
  b.report { n.times{|x| ret(x)}}
  b.report { n.times{|x| nret(x)}}
end

#Results:
#  user     system      total        real
#0.030000   0.000000   0.030000 (  0.038025)
#0.020000   0.000000   0.020000 (  0.026663)

# But not as much in JRuby
#     user     system      total        real
#0.051000   0.000000   0.051000 (  0.051000)
#0.045000   0.000000   0.045000 (  0.045000)

Scaling an Array

This method will take an array and adjust its length to a given integer. It will either prune or pad elements depending on if the length is larger or smaller.

class Array  
  # returns a new array which has the same length as n
  # has its members padded or reduced to match the new length 
  def scale(n)
    out = [].fill(nil, 0, n)
    m = (self.length).to_f/n.to_f
    out.each_with_index {|_, i| out[i] = self[(i*m).floor]}
  end
end

[:a,:b,:c,:d].scale(9) #=> [:a, :a, :a, :b, :b, :c, :c, :d, :d]
[:a,:b,:c,:d].scale(2) #=> [:a, :c]

Saving a grayscale image as a true color image in RMagick.

By default RMagick will save an image with no color as a grayscale image. Some applications, like ffmpeg, do not deal well with 8bit grayscale images.

Just add an option when writing the file to force the image_type.

image.write(source) {self.image_type = Magick::TrueColorType}

RMovie

RMovie is a gem for ruby which creates a simple interface to ffmpeg.

# Configure ffmpeg for RMovie with a shared library:
./configure  --enable-libmp3lame --enable-shared --prefix=/usr/local

In version of 0.51 of RMovie there appears to be a memory leak. So call GC.start after opening a movie.

movie = RMovie::Movie.new("quicktime.mov")
GC.start

Caller

# See the file and line of the caller
caller.grep(/\/app\//).first