Two Coding Gotchas: Javascript & Ruby
Why don't you subscribe to my blog while you're here? I'm a freelance web developer and I blog about Ruby, Rails, and business online.
Go ahead and subscribe to my RSS feed. Thanks for visiting!
Nailed by two coding gotchas in two days. Argh!
Here’s the one in Javascript.
js> var a = (100).toFixed(2); js> a 100.00 js> var b = (20).toFixed(2); js> b 20.00 js> a > b false
a is 100.00, and b is 20.00. 100.00 is greater than 20.00 right? Yes, except that they’re strings! toFixed returns strings, and any comparison is a string comparison and not a numeric comparison!
Now, here’s the Ruby one that got me. If you’re not a Ruby person then this one might be a little harder to pick.
irb(main):001:0> class Klass irb(main):002:1> def meth=(value) irb(main):003:2> return 'return this please' irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> irb(main):007:0* obj = Klass.new => #<Klass:0x83180> irb(main):008:0> obj.meth = "Do not return this please" => "Do not return this please"
Well, I wanted to return “return this please” on the assignment, but instead Ruby ignored me and returned the value of the assignment instead. What if I want to indicate that the assignment failed? My only option is to throw an exception.
I can appreciate that Ruby wants to keep things consistent and always return the assignment value, but can Ruby appreciate my view of consistency and return when I say to return!
If you can tell me why Ruby behaves this way I would appreciate it if you could leave your mark in my comments section.
Save To Delicious