Search this site


Metadata

Articles

Projects

Presentations

Riding on the failboat: Ruby, episode 1.

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)
=> 0
Unexpected.

2 responses to 'Riding on the failboat: Ruby, episode 1.'

Showing last 2 comments... (Click here to view all comments)

jesse wrote at Wed May 7 11:59:43 2008...
You may want to look into calling methods of an object rather than passing the object to something. It usually has much nicer results.

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.

anon wrote at Tue May 27 05:37:07 2008...
jesse: you call this "nice" ?

"ABC".to_i
=> 0

I call this "useless" because of its inability to report problems. Back to old "atoi", things evolved since, but this one painfully drags you back in time.


Leave a reply

You need javascript enabled to use this form. Anti-spam efforts ongoing. Also, if the comment doesn't show up, it's because the form expired. Go back and copy your comment, reload the form, and resubmit. Apologies if this is a hassle, I'm just playing with antispam methods right now. If this insists on not working, please email me about it.

Name (required)
E-mail (optional, if you want me to be able to email you back)
URL (also optional)
Comment: