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.