Ruby Flare

Your awesome Tagline

1 note

Beware of shortcuts

Here’s a bit of code that caused a failure today:

scenario.illustrations << illustration if illustration = Illustration.find_by_code(legacy_scenario_illustration.IllustNo)   

The if condition was added to ensure that only non-nil values are added to the scenario.illustrations collection. It uses the convenience of making the assignment of the local variable illustration inside the if condition. But when ruby parses that line, the first use of illustration is not yet defined as a local variable so it is assumed to belong to self, which is definitely not the desired effect.

The fix was simply to use two lines:

illustration = Illustration.find_by_code(legacy_scenario_illustration.IllustNo)
scenario.illustrations << illustration if illustration.present?

Now ruby knows illustration is a local variable instead of a method of self.

Filed under ruby

  1. rubyflare posted this