class Array
Ruby’s core Array
class. See documentation for version 2.1.5, 2.0.0, or 1.9.3.
Public Instance Methods
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]]
# File lib/reactive_support/core_ext/object/deep_dup.rb 36 def deep_dup 37 self.map {|item| item.deep_dup } 38 end
The #extract_options!
method retrieves a hash of options from the end of a set of splat args. If the last element of the set is Hash
or instance of another class implementing the #extractable_options?
method, #extract_options!
method pops and returns that object. Otherwise, it returns an empty Hash
.
# File lib/reactive_support/core_ext/array/extract_options.rb 22 def extract_options! 23 return last.is_a?(Hash) && last.extractable_options? ? pop : {} 24 end
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) # => []
# File lib/reactive_support/core_ext/array/access.rb 16 def from(position) 17 self[position, length] || [] 18 end
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
# File lib/reactive_support/core_ext/object/blank.rb 84 def present? 85 !blank? 86 end
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) # => []
# File lib/reactive_support/core_ext/array/access.rb 31 def to(position) 32 self[0..position] 33 end