Array
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.
Included modules
- Enumerable
Files
- array.c
- lib/abbrev.rb
- lib/pp.rb
- lib/rexml/xpath_parser.rb
- lib/shellwords.rb
- lib/yaml/rubytypes.rb
2Notes
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.
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