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













