Advanced statements with Ruby
Posted by Sandro Paganotti in
Ruby on Rails -
1 comment
Yesterday I was playing with statements trying to find out an elegant way to solve a problem:
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 is empty). Plus I had to execute 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 available through the ‘at(pos)’ method where pos is the index of the column (starting from 0). This is the solution I come across:
worksheet.each(3) do |row|
break if ((value=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 assignment come from the second or the third column (remember that when the first condition in an ‘and’ clause isn’t met the interpreter doesn’t execute the second, thus div remains nil if row.at(2) is not nil).
Hope this could help. Sandro


Comments
Dave
Posted on June 30