/ ruby

Looks Like A Bug

A common feature of "cool" code bases is the inclusion of code one may not understand at first glance, or worse may consider a bug. Consider the following snippet.

Assignment In Condition

This ruby program reads lines from standard input and prints the first word in every line that has a first word:

while line = gets&.chomp do  
  if m = line.match(/^(\w+)\b/)
    puts "The first word was: #{m[1]}"
  end
end

And the nice thing is that it works. Of course the not so nice thing is the assignment in condition, because it looks like a bug. Anyone who has mistakenly used a single equal sign instead of the double equal had encountered the buggy version of it. And so this code sets the alarm for many developers.

An obvious alternative is to separate the condition from the assignment:

captured = line.match(/^(\w+)\b/)
if captured
    puts "The first word was: #{captured[1]}"
end

The second assignment in condition is the outer while loop. Ruby gives us the tools to refactor it as well:

ARGF.each_line do |line|
    captured = line.match(/^(\w+)\b/)
    if captured
        puts "The first word was: #{captured[1]}"
    end
end

Same functionality, different syntax and now everything seems to have been put there on purpose.