Riding on the failboat: Ruby, episode 1.
Posted Tue, 06 May 2008
I'm quickly learning ruby at my new job. Today's POLA (principle of least
astonishment) violation is blamed on my expectations of 'if' behavior in Ruby
from what I know from Python, C, and other languages.
Non-nil values are considered true:
["0", [], {}, "", 0, true, false, nil].each { |x|
bool = (x) ? true : false
puts "#{x.inspect}: #{bool}"
}
"0": true
[]: true
{}: true
"": true
0: true
true: true
false: false
nil: false
I mostly expected every one of the outputs here except for the literal 0 value
being true. Noted for future reference.
Additionally confusing, is that Integer() will barf on most non-number inputs, but for some reason "nil" means 0.
irb(main):002:0> Integer(nil) => 0Unexpected.
Example:
irb(main):001:0> Integer("ABC")
ArgumentError: invalid value for Integer: "ABC"
from (irb):1:in `Integer'
from (irb):1
irb(main):002:0> "ABC".to_i
=> 0
And
irb(main):003:0> Integer("123D45")
ArgumentError: invalid value for Integer: "123D45"
from (irb):3:in `Integer'
from (irb):3
from :0
irb(main):004:0> "123D45".to_i
=> 123
Hope that helps.