Ruby vs. PHP, round #19238 2

Posted by Matt on August 25, 2008

I just translated an old PHP function to its Ruby counterpart. I think it really showcases Ruby's elegance:

PHP Version:


function calc_pct_complete($job_id, $d) {
  $pc = 0;
  $sql = "some SQL query";
  $res = mysql_query($sql);
  while ($row = mysql_fetch_array($res)) {
    $x = total_days($row[start_date], $d) / total_days($row[start_date], $row[end_date]);
    if ($x < 0) {
      $x = 0;
    } elseif ($x > 1) {
      $x = 1;
    } elseif ($row[name] != "X" && $row[name] != "Y") {
      $x = $x * $x;
    }
    $pc += $x * $row[pct_hours];
  }
  mysql_free_result($res);
  return $pc;
}

Ruby Version:


def percentage_complete(date = Date.today)
  self.phases.inject(0.0) do |sum, phase|
    percent_complete = phase.percentage_complete(date)
    percent_complete = percent_complete ** 2 unless %w{X Y}.include?(phase.name)

    sum += (percent_complete * phase.percentage_of_hours)
  end
end
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Nuno Mon, 25 Aug 2008 17:27:42 PDT

    Pretty cool, indeed. Thanks for sharing. I’m in the process of deciding which dynamically-typed programming language I’m going to learn next, and your constant praise of Ruby definitely makes me increasingly curious. Being a Java developer, I’m obviously considering Groovy [groovy.codehaus.org/], but also Python and Ruby.

  2. Matt Mon, 25 Aug 2008 17:43:59 PDT

    Haven’t tried Groovy yet, but I’ve done both Java and Python in the past. All three have their strong points, but Ruby makes me remember why I like programming. It gives me powerful, elegant tools and then steps to the side, allowing me to do what I needs to get done.

Comments