Moving Elements in Ruby Arrays

warning: Invalid argument supplied for foreach() in /home/snuxoll/snuxoll.com/modules/jaikublock/jaiku.module on line 259.

Tagged:  

    Today in my coding of droppit I needed to keep an ordered list of mimetypes sorted by priority, as such I needed some way to 'move' them around the array. Since there is no included way in the ruby Array class to do this, with the help of my friends in #ruby on freenode I have this snippet of code for you.

# Mixin for Array that allows you
# to move elements arround easily
module Reorderable
  def move(from, to)
    insert(to, delete_at(from))
  end
end

Here's some example usage

priorities = ['text/uri-list', 'x-mozilla/link']
priorities.extend(Reoderable)
priorities.move(1, 0)
priorities => ['x-mozilla/link', 'text/uri-list']

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

Content Copyright ©2008 Stefan Nuxoll