Ruby, iOS, and Other Development

A place to share useful code snippets, ideas, and techniques

All code in posted articles shall be considered public domain unless otherwise noted.
Comments remain the property of their authors.

2006-12-30

Randomizing an Array and Other FAQs

This is a quickie, but I'm so incredibly tired of seeing it on the ruby-talk list (and occasionally Rails list) that I'm posting it anyway. It's also (kinda, sorta) a followup to the previous post.

If you need to randomize an array, use the following:

random_array = my_array.sort_by{rand}

Now quit asking about it. Here are some other little FAQs I'm tired of seeing on the lists:

  • Symbols can be thought of as immutable, internalized strings if you like, but strings and symbols are, indeed, different. If you really need to know more you can search the web, since others have covered it in more depth.
  • Hashes are unordered. Deal with it. There is no good reason for a hash to maintain the order of its keys; the purpose of a hash is amortized constant time lookup. If you need to iterate through the hash keys in some order, use #sort or #sort_by before iterating.
  • Rails has a bunch of stuff added to Ruby. This includes things like HashWithIndifferentAccess (which allows the params hash to be accessed by string or symbol) and Symbol#to_proc (which lets you use &:foo in place of {|x|x.foo}). Ruby Facets makes some of that available to normal Ruby. Ruby 2.0 will also have some of it built in.
  • Rails isn't the only thing Ruby is good for. For that matter, it is neither the only Ruby web framework, nor is ActiveRecord the only Ruby ORM.

Phew. Are we done? Anyone else want to post their pet peeve FAQ? Leave a comment. Oh, yeah, almost forgot.

Enjoy!

Updated! See Randomizing an Array Revisited.

Labels: , ,

3 Comments:

  • At 12/24/2007 02:20:00 AM, Anonymous Anonymous said…

    Hey thanks for the cool randomize array trick!

    (i was just going to ask on the IRC channel about it)

     
  • At 1/07/2008 05:44:00 AM, Anonymous Anonymous said…

    The array shuffling tip is not very good, see my blog entry on this subject. In short it has O(n log n) complexity (same as sort) while array can by shuffled in O(n) time. So I wouldn't recommend it for shuffling very big arrays. Or making it a library function.

     
  • At 1/07/2008 09:50:00 AM, Blogger Gregory said…

    You are, of course, correct. I added a post on it and linked to your blog.

     

Post a Comment

<< Home