Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Aug 23 ’10

Use negative Array indices

Ruby arrays have some nifty behavior when passed negative array indices. Let’s say you have an array

array = [:a, :b, :c, :d, :e]

You can access the last element in the array by calling

array[-1] # => :e

The second-to-last element has index -2, and so on. Negative indices also work for slicing operations. For example, if you wanted to leave out the last two elements in the array, you would call

array[0..-3] # => [:a, :b, :c]

and if you wanted to remove just the first element of the array,

array[1..-1] # => [:b, :c, :d, :e]

This tip was submitted by Rockwell Schrock.

3 notes 0 comments

  1. morygonzalez reblogged this from rubyquicktips
  2. Rockwell Schrock submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus