Sha256: fbb85147068f1e90a6b5a086f7fe10306e3fcea47a12bed6b33474ada2593084

Contents?: true

Size: 1.64 KB

Versions: 1

Compression:

Stored size: 1.64 KB

Contents

require 'facet/array/store'
class Array

  # Modifies #[] to accept a multiple indexes.
  #
  #   require 'facet/array/[]'
  #
  #   a = ['a','b','c','d','e','f']
  #
  #   a[1]        #=> 'b'
  #   a[1,1]      #=> ['b','b']
  #   a[0,2,4]    #=> ['a','c','e']
  #   a[1,1,1]    #=> ['b','b','b']
  #
  # WARNING: Use with caution! This will cause other routines,
  # which use the array[start,length] notation to no longer
  # work. If you feel passinate about it, make sure all other
  # routines use #slice or facet's own #get method instead.
  def [](*args)
    return values_at(*args) if args.length > 1
    return slice(*args)
  end

  # Add slicing to element assignment operator. If an Array
  # is passed as the assignment then each element will
  # be assigned to the corresponding index. The shorter
  # of the two determine how many to assign.
  #
  #   require "facet/array/[]"
  #
  #   h = [1,2,3]
  #
  #   h[0,1] = [10,11]       #=> [10,11]
  #   h                      #=> [10,11,3]
  #
  #   h[0,1] = [12,13,14]    #=> [12,13]
  #   h                      #=> [12,13,3]
  #
  #   h[0,1] = [15]          #=> [15]
  #   h                      #=> [15,13,3]
  #
  # If any other object is passed as assignment
  # then all indexes will be assigned that same object.
  #
  #   h[0,1] = 99            #=> [99,99]
  #   h                      #=> [99,99,3]
  #
  def []=(*args)
    return store( *args ) if args.length <= 2
    aVals = args.pop
    aVals = [aVals] * args.length unless aVals.kind_of?( Array )
    n = (args.length <= aVals.length ? args.length : aVals.length)
    n.times{ |i| store( args[i], aVals[i] ) }
    return aVals.slice(0,n)
  end

end 

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.6.3 lib/facet/array/[].rb