Class: Array

Inherits:
Object show all
Defined in:
lib/reactive_support/core_ext/object/blank.rb,
lib/reactive_support/core_ext/array/access.rb,
lib/reactive_support/core_ext/object/deep_dup.rb

Overview

Ruby’s core Array class. See documentation for version 2.1.3, 2.0.0, or 1.9.3.

Instance Method Summary collapse

Instance Method Details

#deep_dupObject

When called on an array, the #deep_dup method duplicates all the members of the array recursively, so that actions on the duplicate do not affect the original:

arr = [1, 2, [3, 4]]                  # => [1, 2, [3, 4]]
dup, deep = arr.dup, arr.deep_dup     # => [1, 2, [3, 4]], [1, 2, [3, 4]]

deep[2][1] = 5                        # => [1, 2, [3, 5]]
p arr                                 # => [1, 2, [3, 4]]

dup[2][1] = 5                         # => [1, 2, [3, 5]]
p arr                                 # => [1, 2, [3, 5]]


29
30
31
# File 'lib/reactive_support/core_ext/object/deep_dup.rb', line 29

def deep_dup
  self.map {|item| item.deep_dup }
end

#from(position) ⇒ Object

The #from method returns the tail of the array starting at the given position.

[1, 2, 3, 4, 5].from(2)     # => [3, 4, 5]
[1, 2, 3, 4, 5].from(0)     # => [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5].from(-2)    # => [4, 5]

#from returns an empty array if the receiving array is empty, the given position exceeds the maximum index of the array, or the given position is lower than the array’s minimum (i.e., largest negative) index.

[].from(0)                  # => []
[1, 2, 3, 4, 5].from(10)    # => []
[1, 2, 3, 4, 5].from(-10)   # => []


16
17
18
# File 'lib/reactive_support/core_ext/array/access.rb', line 16

def from(position)
  self[position, length] ||  []
end

#present?Boolean

When called on an array, the #present? method returns true if the array has any elements. Note that #present? also returns true if the array consists of blank values:

['foo', 'bar'].present?    # => true 
[false, nil].present?      # => true 
[].present?                # => false

Returns:

  • (Boolean)


56
57
58
# File 'lib/reactive_support/core_ext/object/blank.rb', line 56

def present?
  !blank?
end

#to(position) ⇒ Object

The #to method returns the beginning of the array up to and including the given position.

[1, 2, 3, 4, 5].to(2)       # => [1, 2, 3]
[1, 2, 3, 4, 5].to(10)      # => [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5].to(-2)      # => [1, 2, 3, 4]

#to returns an empty array if the receiving array is empty or the given position falls below the minimum (negative) index.

[].to(0)                    # => []
[1, 2, 3, 4, 5].to(-10)     # => []


31
32
33
# File 'lib/reactive_support/core_ext/array/access.rb', line 31

def to(position)
  self[0..position]
end