Case statement pitfall when migrating to Ruby 1.9
Posted: August 1, 2011 Filed under: code example, ruby Leave a comment »I have been using Rubinius 2.0 to run machine learning experiments with libsvm lately. When running in Ruby 1.9.2, I noticed that my classifier always classified all samples as negative. I though this was caused by issues with libsvm-ruby-swig so I recompiled libsvm-ruby-swig from scratch including rerunning swig, but nothing changed. Next, I changed to use libsvmffi instead, but the result was the same. Realizing that I actually had some tests running av very simple classifier and that these tests passed on 1.9.2 made me look closer at the code. What I found was that the behavior of the Ruby case statement has changed from 1.8.7 to 1.9.2.
For if statements, 1 is equal to 1.0 in both 1.8.7 and 1.9, but while 1 matches 1.0 in 1.8.7 case statements, it does not in 1.9.2.
Code snippet that shows the difference:
#!/usr/bin/env ruby puts case 1.0 when 1 "yay" else "nay" end
First the output of irb when running 1.8.7:
$ rvm use ruby-1.8.7 Using /usr/local/rvm/gems/ruby-1.8.7-p334 $ ./case.rb yay
And the same in 1.9.2:
$ rvm use ruby-1.9.2 Using /usr/local/rvm/gems/ruby-1.9.2-p180 $ ./case.rb nay
Needless to say, I was puzzled by this result, but I was more surprised by the 1.8.7 behavior than 1.9.2. My assumption when I wrote the code was that I was dealing with integer values and since it worked, I forgot about it. Next time you see different behavior between 1.8.7 and 1.9.2 it might be worth reviewing case statements.