Saari Development

Ali Rizvi's Technical Blog as a Professional Software Development Engineer

Archive for the ‘ruby’ Category

Rails: Non-DB field in Model with validation

leave a comment »

Challenge: Add a field to the model representing system date, time & timezone that is not stored in the database and have validation on it.


  • Add attr_accessor & attr_accessible (for bulk update), add getter (sys_date_time) & setter (sys_date_time=) methods.
  • Return system date time in UTC from getter and show in user (browser) timezone on client side (using moment-timezone.js which is moment.js extension select the download with timezone data)
  • When the setting come to be saved using update_attributes in controller it eventually calls model setter (sys_date_time=) where you convert it back to utc given the timezone info (ActiveSupport::Timezone[zone] is your friend with ActiveSupport::TimeZone[zone].parse then in_time_zone(‘UTC’))
  • Validation is tricky as this is not a db backed and getter returns the calculated value which is always valid. You need to validate input first thing in setter and set a new member variable with errors found. Then add a validate do … end block where you iterate through the new member variable with errors and do errors.add(attr, message).

Will add code snippets when time permits.



Written by imsaar

April 7, 2016 at 2:02 pm

Posted in code, rails, ruby

Ruby: TPK Algorithm in Different Programming Languages

leave a comment »

I was looking for some exercise problems for a programming class I am teaching and encountered Knuth’s TPK problem on comparing solutions in different languages but did not find my favorite language and thought I would do it in Ruby and may be submit for inclusion there.

The TPK algorithm reads in an array of 11 values, applies a particular function to each value, and then writes the result in reverse order. It serves just to illustrate some of the usual actions that an imperative programming language must perform.

Here is my quick solution:

inputs = []

def f(x)
  Math.sqrt(x.abs) + (5 * x ** 3)

11.times do
  inputs << gets.chomp.to_f

inputs.reverse.each_with_index do |num, index|
  fn = f(num)
  if fn < 400
    puts "#{10 - index} #{fn}"
    puts "#{10 - index} #{fn} TOO LARGE"

I think it could be done better but just wanted to have something out there.

Written by imsaar

August 28, 2013 at 2:33 pm

Posted in ruby

Vim: Using Ruby Regular Expression

leave a comment »

I needed to remove line number from a web copy-pasted code snippet. I know there is a way to configure vim to use the perl style regular expressions but I couldn’t find how quickly.

What I found was:

:rubydo gsub /pattern/,'replacement'</code>

Here is my specific command:

:rubydo gsub /^\s+\d{0,3}\s/, ''

Pre-requisite: look for +ruby in :ver output (if it is -ruby then it would not work).

The above web page also talks about Perl regular expression in Vim and different ways to do that.

Written by imsaar

August 28, 2013 at 2:17 pm

Posted in ruby, vim

Ruby: Add a prefix to all files in a directory

leave a comment »

I found myself looking for a way to rename all files in a directory by appending a prefix and couldn’t find a utility to do such a renaming after quick search so I wrote my own.

# Quick script to bulk prepend prefix to filenames to all files in a directory
# Also strips any spaces in the filename
# Example usage : ruby prepend_rename.rb Disc1_ C:\AudioBook\Disc1\

raise "Prefix and Directory are required" if ARGV.size < 2

prefix = ARGV[0]
dir = ARGV[1]

raise "Non-word character prefix #{prefix}" unless prefix =~ /^\w+$/
raise "No such directory: #{dir}" unless Dir.exists?(dir)

Dir.entries(dir).each do |file|
 next if
 new_name = prefix + file.gsub(/\s+/, '')
 File.rename(file, new_name)

Written by imsaar

February 7, 2010 at 6:11 pm

Posted in code, ruby, windows

Ruby: String += vs <<

with 2 comments

Learned this interesting tidbit on Seattle.rb mailing list that appending a string with << is 10 times more efficient than +=. This would matter if you are doing a lot of string concatenation.

From: Joe Van Dyk
Date: Fri, Nov 20, 2009 at 10:20 AM
Subject: Re: [Ruby] += vs <<
To: Seattle Ruby Brigade!

$ cat t.rb
require 'benchmark'

long_string = 's' * 100000000
another_long_string = 'y ' * 1000 do |b|"<<") { long_string << another_long_string }"+=") { long_string += another_long_string }

$ ruby t.rb
user system total real
<< 0.000000 0.020000 0.020000 ( 0.022544)
+= 0.110000 0.130000 0.240000 ( 0.250046)

Update: Later in this thread mentioned a comprehensive blog entry about this topic : The Fastest Way to Concatenate Strings and Arrays in Ruby

Written by imsaar

November 20, 2009 at 8:44 pm

Posted in ruby

Rails: Skipping Base Class Filters in Subclasses

with 3 comments

I encountered a case where we needed to skip a filter as it was causing infinite redirection in a subclass. I found my answer in: Rails Filters Documentation

Filter chain skipping

Declaring a filter on a base class conveniently applies to its subclasses, but sometimes a subclass should skip some of its superclass’ filters:

  class ApplicationController < ActionController::Base
    before_filter :authenticate
    around_filter :catch_exceptions

  class WeblogController < ApplicationController
    # Will run the :authenticate and :catch_exceptions filters.

  class SignupController < ApplicationController
    # Skip :authenticate, run :catch_exceptions.
    skip_before_filter :authenticate

  class ProjectsController < ApplicationController
    # Skip :catch_exceptions, run :authenticate.
    skip_filter :catch_exceptions

  class ClientsController  :index

Written by imsaar

November 10, 2009 at 9:07 pm

Posted in code, documentation, rails, ruby

JRuby: Stochastic Simulation with SSJ

with 2 comments

I needed to work on a simulation project that involved working with the SSJ java library.
If I haven’t mentioned before I love Ruby (the programming language) and Java, though a tool in my toolkit, does not evoke the same feeling.

So my first reaction was I can use JRuby to benefit from the existing java library and beauty of Ruby.
The SSJ library comes with a comprehensive sets of examples and documentation. I started exploring that.

Fortunately at RubyConf 2008 with some help from Charles Nutter I was able to install jruby on my laptop, getting jruby installed and running was not trivial. I wish somebody can do a one click installer for jruby same as they did for Ruby and Rails.

I downloaded SSJ and unzipped the downloaded file containing jar files into C:\Program Files\Java\jdk1.6.0_02\lib\ext directory. Added the CLASSPATH variable in my windows environment set to this directory.

I tried the following example from examples.pdf

import umontreal.iro.lecuyer.rng.*;
import umontreal.iro.lecuyer.stat.*;
public class Collision {
    int k; // Number of locations.
    int m; // Number of items.
    double lambda; // Theoretical expectation of C (asymptotic).
    boolean[] used; // Locations already used.
    public Collision (int k, int m) {
        this.k = k;
        this.m = m;
        lambda = (double) m * m / (2.0 * k);
        used = new boolean[k];
    // Generates and returns the number of collisions.
    public int generateC (RandomStream stream) {
        int C = 0;
        for (int i = 0; i < k; i++) used&#91;i&#93; = false;
        for (int j = 0; j < m; j++) {
            int loc = stream.nextInt (0, k-1);
            if (used&#91;loc&#93;) C++;
            else used&#91;loc&#93; = true;
        return C;
    // Performs n indep. runs using stream and collects statistics in statC.
    public void simulateRuns (int n, RandomStream stream, Tally statC) {
        for (int i=0; i<n; i++) statC.add (generateC (stream));
        System.out.println ( (0.95, 3));
        System.out.println (" Theoretical mean: " + lambda);
    public static void main (String&#91;&#93; args) {
        Tally statC = new Tally ("Statistics on collisions");
        Collision col = new Collision (10000, 500);
        col.simulateRuns (100000, new MRG32k3a(), statC);

I compiled and ran the Java code above to ensure I was getting the same results using the following steps:
javac -cp "C:\Program Files\Java\jdk1.6.0_02\lib\ext\ssj.jar"
java -cp "C:\Program Files\Java\jdk1.6.0_02\lib\ext\ssj.jar;C:\code\ruby\jruby" Collision

As you can notice my code was in the C:\code\ruby\jruby directory and I was in this directory when I ran the above program.

Here is the same code example in jruby code:

require 'java'
require 'ssj.jar'

import 'umontreal.iro.lecuyer.rng.RandomStream'
import 'umontreal.iro.lecuyer.stat.Tally'
import 'umontreal.iro.lecuyer.rng.MRG32k3a'

class Collision
  def initialize(k, m)
    @k = k
    @m = m
    @lambda = m * m / (2.0 * k)
    @used =, false)

  def generate_c(stream)
    c = 0
    @k.times { |i| @used[i] = false }
    @m.times do |j|
      loc = stream.nextInt(0, @k-1)
      if @used[loc]
        c += 1
        @used[loc] = true
    return c

  def simulate_runs(n, stream, stat_c)
   n.times { stat_c.add(generate_c(stream)) }
   puts, 3)
   puts " Theoretical mean: #{@lambda} "

    stat_c ="Statistics on collision")
    col =,500)
    col.simulate_runs(100000,, stat_c)


The jruby code runs comparatively slower (my feeling is 5 times slower but I will measure and add it later). I am using the latest available jruby 1.1.5 at the time of this post.

Update: The JRuby version takes around 13 minutes while the equivalent Java code above takes 17 seconds. This seems to be unacceptable performance, I am not sure if this is specific to SSJ or other libraries too. If I understand correctly, JRuby should be running inside the JVM and when I call SSJ library that is the same Java code that runs so I don’t understand why it is so slow unless I have used some technique that slows down my JRuby version.

Written by imsaar

November 15, 2008 at 10:25 pm

Posted in code, java, jruby, ruby