Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

Show files where this class is defined (6 files)
Register or log in to add new notes.
February 12, 2009
4 thanks

Literal syntax

As you propably know you can create an Array either with the constructor or the literal syntax:

Array.new == []
# => true

But there is also another nice and concise literal syntax for creating Arrays of Strings:

["one", "two", "three"] == %w[one two three]
# => true

You can use any kind of parenthesis you like after the %w, either (), [] or {}. I prefer the square brackets because it looks more like an array.

June 11, 2012
0 thanks

more_than? instance method

Over the weekend I kept running into instances where I was writing code like this:

Code example

arr = ['hello', 'world']

if arr.length > 2
 # do stuff
else
 # do something else
end

So I ended up extending the core and adding an instance method of more_than?

Code example

class Array
  def more_than?(num)
    length > num
  end
end

Usage

arr = ['hello', 'world']
puts "Hello" if arr.more_than? 1