Ruby Language


Arrays All Versions

1.6.8
1.8
1.9
2.0
2.1
2.2
2.3

This draft deletes the entire topic.

inline side-by-side expand all collapse all

Examples

  • 5

    Arrays of strings can be created using ruby's percent string syntax:

    array = %w(one two three four)
    

    This is functionally equivalent to defining the array as:

    array = ['one', 'two', 'three', 'four']
    

    Instead of %w() you may use other matching pairs of delimiters: %w{...}, %w[...] or %w<...>.

    It is also possible to use arbitrary non-alphanumeric delimiters, such as: %w!...!, %w#...# or %w@...@.

    %W can be used instead of %w to incorporate string interpolation. Consider the following:

    var = 'hello'
    
    %w(#{var}) # => ["\#{var}"]
    %W(#{var}) # => ["hello"]
    
  • 4

    An empty Array ([]) can be created with Array's class method, Array::new:

    Array.new    
    

    To set the length of the array, pass a numerical argument:

    Array.new(3)
    

    This returns an array with three nil-values [nil, nil, nil].

    To set the value of the elements in the array, add a second argument with the desired value:

    Array.new(3, :x)
    

    This returns [:x, :x, :x].

    Instead of a second argument, it's also possible to pass a block, which will be evaluated for each index of the array to generate the array elements.

    Array.new(4) { foo(bar) }
    

    This returns an array with 4 elements, each equal to foo(bar).

    The main reason to use a block is to pass the index of the element as an argument. Here are a few examples:

    Array.new(3) { |i| i + 1 }                   #=> [1, 2, 3]
    Array.new(3) { |i| i * 2 }                   #=> [0, 2, 4]
    Array.new(3) { |i| Array.new(i + 1, i + 1) } #=> [[1], [2, 2], [3, 3, 3]]
    
  • 3

    This requires Ruby 2.0 or higher.

    array = %i{one two three four}
    

    Creates the array [:one, :two, :three, :four].

    Instead of %i{...}, you may use %i(...) or %i[...] or %i!...!.

I am downvoting this example because it is...

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a Arrays question? Ask Question

Create Array of Strings

5

Arrays of strings can be created using ruby's percent string syntax:

array = %w(one two three four)

This is functionally equivalent to defining the array as:

array = ['one', 'two', 'three', 'four']

Instead of %w() you may use other matching pairs of delimiters: %w{...}, %w[...] or %w<...>.

It is also possible to use arbitrary non-alphanumeric delimiters, such as: %w!...!, %w#...# or %w@...@.

%W can be used instead of %w to incorporate string interpolation. Consider the following:

var = 'hello'

%w(#{var}) # => ["\#{var}"]
%W(#{var}) # => ["hello"]

Create Array with Array::new

4

An empty Array ([]) can be created with Array's class method, Array::new:

Array.new    

To set the length of the array, pass a numerical argument:

Array.new(3)

This returns an array with three nil-values [nil, nil, nil].

To set the value of the elements in the array, add a second argument with the desired value:

Array.new(3, :x)

This returns [:x, :x, :x].

Instead of a second argument, it's also possible to pass a block, which will be evaluated for each index of the array to generate the array elements.

Array.new(4) { foo(bar) }

This returns an array with 4 elements, each equal to foo(bar).

The main reason to use a block is to pass the index of the element as an argument. Here are a few examples:

Array.new(3) { |i| i + 1 }                   #=> [1, 2, 3]
Array.new(3) { |i| i * 2 }                   #=> [0, 2, 4]
Array.new(3) { |i| Array.new(i + 1, i + 1) } #=> [[1], [2, 2], [3, 3, 3]]

Create Array of Symbols

3

This requires Ruby 2.0 or higher.

array = %i{one two three four}

Creates the array [:one, :two, :three, :four].

Instead of %i{...}, you may use %i(...) or %i[...] or %i!...!.

Creating an Array with []

2

Arrays can be created by enclosing a list of elements in square brackets ([ and ]). Array elements in this notation are separated with commas:

array = [1, 2, 3, 4]

Ruby arrays can contain any combination of types, including nil and other arrays:

array = [1,'b', nil, [3, 4]]

#map

1

#map, provided by Enumerable, creates an array by invoking a block on each element and collecting the results:

[1, 2, 3].map { |i| i * 3 }
# => [3, 6, 9]

['1', '2', '3', '4', '5'].map { |i| i.to_i }
# => [1, 2, 3, 4, 5]

The original array is not modified; a new array is returned containing the transformed values in the same order as the source values.

In map method you can call method or use proc to all elements in array.

# call to_i method on all elements
%w(1 2 3 4 5 6 7 8 9 10).map(&:to_i)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# using proc (lambda) on all elements
%w(1 2 3 4 5 6 7 8 9 10).map(&->(i){ i.to_i * 2})
# => [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Accessing elements

1

You can access the elements of an array by their indices. Array index numbering starts at 0.

%w(a b c)[0] # => 'a'
%w(a b c)[1] # => 'b'

You can crop an array using range

%w(a b c d)[1..2] # => ['b', 'c']

This returns a new array, but doesn't affect the original. Ruby also supports the use of negative indices.

%w(a b c)[-1] # => 'c'
%w(a b c)[-2] # => 'b'

Other useful methods

Use first to access the first element in an array:

[1, 2, 3, 4].first #=> 1

Or first(n) to access the first n elements returned in an array:

[1, 2, 3, 4].first(2) #=> [1, 2]

Similarly for last and last(n):

[1, 2, 3, 4].last    # => 4
[1, 2, 3, 4].last(2) # => [3, 4]

Arrays and the splat (*) operator

1

The * operator can be used to unpack variables and arrays so that they can be passed as individual arguments to a method.

This can be used to wrap a single object in an Array if it is not already:

def wrap_in_array(value)
  [*value]
end

wrap_in_array(1)
#> [1]

wrap_in_array([1, 2, 3])
#> [1, 2, 3]

wrap_in_array(nil)
#> []

In the above example, the wrap_in_array method accepts one argument, value.

If value is an Array, its elements are unpacked and a new array is created containing those element.

If value is a single object, a new array is created containing that single object.

If value is nil, an empty array is returned.

This can be useful when working with sets as it allows nil, single values and arrays to be handled in a consistent manner:

def list(values)
  [*values] do |value|
    # do something with value
    puts value
  end
end

list(100)
#> 100

list([100, 200])
#> 100
#> 200

list(nil)
# nothing is outputted

Arrays union, intersection and difference

1
x = [5, 5, 1, 3]
y = [5, 2, 4, 3]

Union (|) contains elements from both arrays, with duplicates removed:

x | y
=> [5, 1, 3, 2, 4]

Intersection (&) contains elements which are present both in first and second array:

x & y
=> [5, 3]

Difference (-) contains elements which are present in first array and not present in second array:

x - y
=> [1]

Filtering arrays

1

Often we want to operate only on elements of an array that fulfill a specific condition:

Select

Will return elements that matche a specific condition

array = [1,2,3,4,5,6]
array.select{ |element| element > 3}
# returns [4, 5, 6]

Reject

Will return elements that do not match a specific condition

array = [1,2,3,4,5,6]
array.reject{ |element| element > 3}
# returns [1, 2, 3]

Both #select and #reject return an array, so they can be chained:

array = [1,2,3,4,5,6]
array.select{ |element| element > 3 }.reject{|elm| elm < 5}
#returns [5,6]

Manipulating Array Elements

1

Adding elements:

[1, 2, 3] << 4
# => [1, 2, 3, 4]

[1, 2, 3].push(4)
# => [1, 2, 3, 4]

[1, 2, 3].unshift(4)
# => [4, 1, 2, 3]

[1, 2, 3] << [4, 5]
# => [1, 2, 3, [4, 5]]

Removing elements:

array = [1, 2, 3, 4]
array.pop
# => 4
array
# => [1, 2, 3]

array = [1, 2, 3, 4]
array.shift
# => 1
array
# => [2, 3, 4]

array = [1, 2, 3, 4]
array.delete(1)
# => 1
array
# => [2, 3, 4]

Combining arrays:

[1, 2, 3] + [4, 5, 6]
# => [1, 2, 3, 4, 5, 6]

[1, 2, 3].concat([4, 5, 6])
# => [1, 2, 3, 4, 5, 6]

[1, 2, 3, 4, 5, 6] - [2, 3]
# => [1, 4, 5, 6]

[1, 2, 3] | [2, 3, 4]
# => [1, 2, 3, 4]

[1, 2, 3] & [3, 4]
# => [3]

You can also multiply arrays, e.g.

[1, 2, 3] * 2
# => [1, 2, 3, 1, 2, 3]

Destructuring

0

Any array can be quickly destructured by assigning its elements into multiple variables. A simple example:

arr = [1, 2, 3]
# ---
a = arr[0]
b = arr[1]
c = arr[2]
# --- or, the same
a, b, c = arr

Preceding a variable with the splat operator (*) puts into it an array of all the elements that haven't been captured by other variables. If none are left, empty array is assigned. Only one splat can be used in a single assignment:

a, *b = arr       # a = 1; b = [2, 3]
a, *b, c = arr    # a = 1; b = [2]; c = 3
a, b, c, *d = arr # a = 1; b = 2; c = 3; d = []
a, *b, *c = arr   # SyntaxError: unexpected *

Destructuring is safe and never raises errors. nils are assigned where there's not enough elements, matching the behavior of [] operator when accessing an index out of bounds:

arr[9000] # => nil
a, b, c, d = arr # a = 1; b = 2; c = 3; d = nil

Destructuring implicitly tries to call to_ary implicitly on the object being assigned. By implementing this method in your type you get the ability to destructure it:

class Foo
  def to_ary
    [1, 2]
  end
end
a, b = Foo.new # a = 1; b = 2

If the object being destructured doesn't respond_to? to_ary, it's treated as a single-element array:

1.respond_to?(:to_ary) # => false
a, b = 1 # a = 1; b = nil

Get unique array elements

0

In case you need to read an array elements avoiding repetitions you case use the #uniq method:

a = [1, 1, 2, 3, 4, 4, 5]
a.uniq
#=> [1, 2, 3, 4, 5]

Instead, if you want to remove all duplicated elements from an array, you may use #uniq! method:

a = [1, 1, 2, 3, 4, 4, 5]
a.uniq!
#=> [1, 2, 3, 4, 5]

While the output is the same, #uniq! also stores the new array:

a = [1, 1, 2, 3, 4, 4, 5]
a.uniq
#=> [1, 2, 3, 4, 5]
a
#=> [1, 1, 2, 3, 4, 4, 5]

a = [1, 1, 2, 3, 4, 4, 5]
a.uniq!
#=> [1, 2, 3, 4, 5]
a
#=> [1, 2, 3, 4, 5]

Inject, reduce

0

Inject and reduce are different names for the same thing. In other languages these functions are often called folds (like foldl or foldr). These methods are available on every Enumerable object.

Inject takes a two argument function and applies that to all of the pairs of elements in the Array.

For the array [1, 2, 3] we can add all of these together with the starting value of zero by specifying a starting value and block like so:

[1,2,3].reduce(0) {|a,b| a + b} # => 6

Here we pass the function a starting value and a block that says to add all of the values together. The block is first run with 0 as a and 1 as b it then takes the result of that as the next a so we are then adding 1 to the second value 2. Then we take the result of that (3) and add that on to the final element in the list (also 3) giving us our result (6).

If we omit the first argument, it will set a to being the first element in the list, so the example above is the same as:

[1,2,3].reduce {|a,b| a + b} # => 6

In addition, instead of passing a block with a function, we can pass a named function as a symbol, either with a starting value, or without. With this, the above example could be written as:

[1,2,3].reduce(0, :+) # => 6

or omitting the starting value:

[1,2,3].reduce(:+) # => 6

Turn multi-dimensional array in a one-dimensional array

0

If you have a multi-dimensional array like this

[1, 2, [[3, 4], [5]], 6]

And you need to make it a simple (i.e. one-dimensional) array, you can use the #flatten method, like this:

a = [1, 2, [[3, 4], [5]], 6]
a.flatten
#=> [1, 2, 3, 4, 5, 6]

Two-dimensional array

0

Ruby does not have built-in support for two-dimensional arrays, but you can create an array that contains arrays inside it:

size1 = 3
size2 = 4
array = size1.times.map { size2.times.map { 0 } }

The array generated above looks like this when printed with p:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

You can read or write to elements like this:

x = array[0][1]
array[2][3] = 2

Topic Outline