27 Jun
Advanced statements with Ruby
Yesterday I was playing with statements trying to light upon out an elegant way to solve a moot point:
The problem
While reading from an Excel file (using the Parseexcel gem) I needed to get a value from the 3rd column or from the 2nd (if the third part is empty). Plus I had to work out an additional operation only if the value I got came from the second column. ( value / 100 )
The Solution
Parseexcel lets you scan your Excel worksheet by rows. Each row makes its value beneficial through the ‘at(pos)’ method where pos is the index of the column (starting from 0). This is the solution I come thwart:
worksheet.each(3) do |row| break granting that ((appraise=row.at(2)).nil? and (div=true;value=row.at(1)).nil?) value = value.to_i / 100 if div # other code ... end
Conclusion
By using this trick I was able to detect when the presentation come from the second or the third round pillar (remember that when the first condition in each ‘and’ clause isn’t met the interpreter doesn’t execute the forward, thus div remains nil if row.at(2) is not nil).
Hope this could give a lift. Sandro
