Shinobu’s Secrets

February 17, 2008

Ruby Quirk – the .shift method when manipulating arrays

Filed under: Ruby — Shinobu @ 8:30 am

One of the principles behind Ruby is the Principle of Least Surprise. So far, in my two months of joy learning and working with Ruby (mostly with the code acting as the backbone behind my primitive text layout engine–like a very very primitive alternative to LaTex), I’ve relied on this principle quite heavily–and successfully. But today, for the first time, I was very unpleasantly surprised.

I’m using the latest stable release of Ruby, version 1.8.6-p111 on Windows. I’ve recreated the same “error” or “bug” using the online live preview of Ruby on Ruby’s home website.

The code:

irb(main):001:0> x = [1,2,3,4]
=> [1, 2, 3, 4]
irb(main):002:0> x.shift.nil?
=> false
irb(main):003:0> x
=> [2, 3, 4]

Am I missing something here? I thought that the .nil? method was always nondestructive! (And that the only kinds of methods that permanently change something always end in “!” like “.gsub!”. Even if I used it as a conditional statement, like, “if x.shift.nil? … “, the use of that statement alone would alter the x array!

I’m pretty sure all the Ruby developers are aware of this–it’s just too blatant. My only suggestion to them is–this kind of behavior seems completely against the, you guessed it, Principle of Least Surprise.

1 Comment »

  1. Ok, the post is somewhat older now, but just to put some light into this: .nil? is non-destructive, but .shift is not, it always removes the first element of the array. See http://www.ruby-doc.org/core/classes/Array.html#M000281

    Comment by Jens — July 8, 2008 @ 2:58 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.