Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Jun 27

Advanced statements with Ruby

Posted by Sandro Paganotti in Ruby on Rails - 1 comment digg this add to delicious

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

    It seems like an overly complex solution. Wouldn't this give you the same results? worksheet.each(3) do |row| value = (row.at(2) || row.at(1) / 100) # other code end

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory