photo
Jordan Sissel
geek

Tue, 06 May 2008

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.

Comments: 2 (view comments)
Tags: , ,
Permalink: /geekery/failboat-ruby-1
posted at: 19:00


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

jesse posted at Wed May 7 14: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 posted at Tue May 27 08: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:


Search this site

Navigation

Metadata

Home About Resume My Code (SVN)

Articles

ARP Security Dynamic DNS with DHCP OpenLDAP+Kerberos+SASL PPP over SSH SSH Security: /bin/false Week of Unix Tools Work Efficiency

Projects

fex firefox tabsearch firefox urledit grok keynav liboverride newpsm (FreeBSD) nis2ldap pam_captcha poor man's backup Solaris audio utility xboxproxy xdotool xmlpresenter xpathtool misc scripts

Presentations

Yahoo! Hack Day '06 Unix Essentials Vi/Vim Essentials

Tag Cloud

Calendar

< May 2008 >
SuMoTuWeThFrSa
     1 2 3
4 5 6 7 8 910
11121314151617
18192021222324
25262728293031

Friends

BarCamp Kent Brewster Tantek Çelik John Resig Wesley Shields Tyler Shields

Technorati