In Files

  • mrbgems/mruby-array-ext/mrblib/array.rb
  • mrblib/array.rb

Array

Array is enumerable

Constants

NONE

Public Class Methods

new(size=0, obj=nil, &block) click to toggle source

Private method for Array creation.

ISO 15.2.12.5.15

 
               # File mrblib/array.rb, line 69
def initialize(size=0, obj=nil, &block)
  raise TypeError, "expected Integer for 1st argument" unless size.kind_of? Integer
  raise ArgumentError, "negative array size" if size < 0

  self.clear
  if size > 0
    self[size - 1] = nil  # allocate

    idx = 0
    while(idx < size)
      self[idx] = (block)? block.call(idx): obj
      idx += 1
    end
  end

  self
end
            

Public Instance Methods

ary & other_ary → new_ary click to toggle source

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 91
def &(elem)
  raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array

  hash = {}
  array = []
  elem.each{|v| hash[v] = true }
  self.each do |v|
    if hash[v]
      array << v
      hash.delete v
    end
  end
  array
end
            
ary - other_ary → new_ary click to toggle source

Array Difference---Returns a new array that is a copy of the original array, removing any items that also appear in other_ary. (If you need set-like behavior, see the library class Set.)

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 55
def -(elem)
  raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array

  hash = {}
  array = []
  elem.each { |x| hash[x] = true }
  self.each { |x| array << x unless hash[x] }
  array
end
            
<=>(other) click to toggle source
Comparison---Returns an integer (-1, 0, or +1)
if this array is less than, equal to, or greater than <i>other_ary</i>.
Each object in each array is compared (using <=>). If any value isn't
equal, then that inequality is the return value. If all the
values found are equal, then the return is based on a
comparison of the array lengths.  Thus, two arrays are
``equal'' according to <code>Array#<=></code> if and only if they have
the same length and the value of each element is equal to the
value of the corresponding element in the other array.

ISO 15.2.12.5.36 (x)

 
               # File mrblib/array.rb, line 147
def <=>(other)
  other = self.__ary_cmp(other)
  return 0 if 0 == other
  return nil if nil == other

  len = self.size
  n = other.size
  if len > n
    len = n
  end
  i = 0
  while i < len
    n = (self[i] <=> other[i])
    return n if n == nil
    return n if n != 0
    i += 1
  end
  len = self.size - other.size
  if len == 0
    0
  elsif len > 0
    1
  else
    -1
  end
end
            
==(other) click to toggle source
Equality---Two arrays are equal if they contain the same number
of elements and if each element is equal to (according to
Object.==) the corresponding element in the other array.

ISO 15.2.12.5.33 (x)

 
               # File mrblib/array.rb, line 104
def ==(other)
  other = self.__ary_eq(other)
  return false if other == false
  return true  if other == true
  len = self.size
  i = 0
  while i < len
    return false if self[i] != other[i]
    i += 1
  end
  return true
end
            
__svalue() click to toggle source

internal method to convert multi-value to single value

 
               # File mrblib/array.rb, line 189
def __svalue
  case self.size
  when 0
    return nil
  when 1
    self[0]
  else
    self
  end
end
            
collect!(&block) click to toggle source

Calls the given block for each element of self and pass the respective element. Each element will be replaced by the resulting values.

ISO 15.2.12.5.7

 
               # File mrblib/array.rb, line 50
def collect!(&block)
  return to_enum :collect! unless block_given?

  self.each_index{|idx|
    self[idx] = block.call(self[idx])
  }
  self
end
            
Also aliased as: map!
compact → new_ary click to toggle source

Returns a copy of self with all nil elements removed.

[ "a", nil, "b", nil, "c", nil ].compact
                  #=> [ "a", "b", "c" ]
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 179
def compact
  result = self.dup
  result.compact!
  result
end
            
compact! → ary or nil click to toggle source

Removes nil elements from the array. Returns nil if no changes were made, otherwise returns ary.

[ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
[ "a", "b", "c" ].compact!           #=> nil
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 196
def compact!
  result = self.select { |e| e != nil }
  if result.size == self.size
    nil
  else
    self.replace(result)
  end
end
            
delete(key, &block) click to toggle source

Delete element with index key

 
               # File mrblib/array.rb, line 176
def delete(key, &block)
  while i = self.index(key)
    self.delete_at(i)
    ret = key
  end
  if ret == nil && block
    block.call
  else
    ret
  end
end
            
each(&block) click to toggle source

Calls the given block for each element of self and pass the respective element.

ISO 15.2.12.5.10

 
               # File mrblib/array.rb, line 12
def each(&block)
  return to_enum :each unless block_given?

  idx, length = -1, self.length-1
  while idx < length and length <= self.length and length = self.length-1
    elm = self[idx += 1]
    unless elm
      if elm == nil and length >= self.length
        break
      end
    end
    block.call(elm)
  end
  self
end
            
each_index(&block) click to toggle source

Calls the given block for each element of self and pass the index of the respective element.

ISO 15.2.12.5.11

 
               # File mrblib/array.rb, line 33
def each_index(&block)
  return to_enum :each_index unless block_given?

  idx = 0
  while(idx < length)
    block.call(idx)
    idx += 1
  end
  self
end
            
eql?(other) click to toggle source
Returns <code>true</code> if +self+ and _other_ are the same object,
or are both arrays with the same content.

ISO 15.2.12.5.34 (x)

 
               # File mrblib/array.rb, line 122
def eql?(other)
  other = self.__ary_eq(other)
  return false if other == false
  return true  if other == true
  len = self.size
  i = 0
  while i < len
    return false unless self[i].eql?(other[i])
    i += 1
  end
  return true
end
            
fetch(index) → obj click to toggle source
fetch(index, default) → obj
fetch(index) { |index| block } → obj

Tries to return the element at position index, but throws an IndexError exception if the referenced index lies outside of the array bounds. This error can be prevented by supplying a second argument, which will act as a default value.

Alternatively, if a block is given it will only be executed when an invalid index is referenced. Negative values of index count from the end of the array.

a = [ 11, 22, 33, 44 ]
a.fetch(1)               #=> 22
a.fetch(-1)              #=> 44
a.fetch(4, 'cat')        #=> "cat"
a.fetch(100) { |i| puts "#{i} is out of bounds" }
                         #=> "100 is out of bounds"
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 241
def fetch(n=nil, ifnone=NONE, &block)
  warn "block supersedes default value argument" if n != nil && ifnone != NONE && block

  idx = n
  if idx < 0
    idx += size
  end
  if idx < 0 || size <= idx
    return block.call(n) if block
    if ifnone == NONE
      raise IndexError, "index #{n} outside of array bounds: #{-size}...#{size}"
    end
    return ifnone
  end
  self[idx]
end
            
fill(obj) → ary click to toggle source
fill(obj, start [, length]) → ary
fill(obj, range ) → ary
fill { |index| block } → ary
fill(start [, length] ) { |index| block } → ary
fill(range) { |index| block } → ary

The first three forms set the selected elements of self (which may be the entire array) to obj.

A start of nil is equivalent to zero.

A length of nil is equivalent to the length of the array.

The last three forms fill the array with the value of the given block, which is passed the absolute index of each element to be filled.

Negative values of start count from the end of the array, where -1 is the last element.

a = [ "a", "b", "c", "d" ]
a.fill("x")              #=> ["x", "x", "x", "x"]
a.fill("w", -1)          #=> ["x", "x", "x", "w"]
a.fill("z", 2, 2)        #=> ["x", "x", "z", "z"]
a.fill("y", 0..1)        #=> ["y", "y", "z", "z"]
a.fill { |i| i*i }       #=> [0, 1, 4, 9]
a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
a.fill(1, 2) { |i| i+1 } #=> [0, 2, 3, 27]
a.fill(0..1) { |i| i+1 } #=> [1, 2, 3, 27]
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 291
def fill(arg0=nil, arg1=nil, arg2=nil, &block)
  if arg0 == nil && arg1 == nil && arg2 == nil && !block
    raise ArgumentError, "wrong number of arguments (0 for 1..3)" 
  end

  beg = len = 0
  ary = []
  if block
    if arg0 == nil && arg1 == nil && arg2 == nil
      # ary.fill { |index| block }                    -> ary
      beg = 0
      len = self.size
    elsif arg0 != nil && arg0.respond_to?(:begin) && arg0.respond_to?(:end)
      # ary.fill(range) { |index| block }             -> ary
      beg = arg0.begin
      beg += self.size if beg < 0
      len = arg0.end - beg + 1
    elsif arg0 != nil
      # ary.fill(start [, length] ) { |index| block } -> ary
      beg = arg0
      beg += self.size if beg < 0
      if arg1 == nil
        len = self.size
      else
        len = arg0 + arg1
      end
    end
  else
    if arg0 != nil && arg1 == nil && arg2 == nil
      # ary.fill(obj)                                 -> ary
      beg = 0
      len = self.size      
    elsif arg0 != nil && arg1 != nil && arg1.respond_to?(:begin) && arg1.respond_to?(:end)
      # ary.fill(obj, range )                         -> ary
      len = self.size
      beg = arg1.begin
      len = arg1.end - beg + 1
    elsif arg0 != nil && arg1 != nil
      # ary.fill(obj, start [, length])               -> ary
      beg = arg1
      beg += self.size if beg < 0
     if arg2 == nil
        len = self.size
      else
        len = arg1 + arg2
      end
    end
  end

  i = beg
  if block
    while i < len
      self[i] = block.call(i)
      i += 1
    end
  else 
    while i < len
      self[i] = arg0
      i += 1
    end
  end
  self
end
            
flatten → new_ary click to toggle source
flatten(level) → new_ary

Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array. If the optional level argument determines the level of recursion to flatten.

s = [ 1, 2, 3 ]           #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ]   #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten(1)              #=> [1, 2, 3, [4, 5]]
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 123
def flatten(depth=nil)
  ar = []
  self.each do |e|
    if e.is_a?(Array) && (depth.nil? || depth > 0)
      ar += e.flatten(depth.nil? ? nil : depth - 1)
    else
      ar << e
    end
  end
  ar
end
            
flatten! → ary or nil click to toggle source
flatten!(level) → array or nil

Flattens self in place. Returns nil if no modifications were made (i.e., ary contains no subarrays.) If the optional level argument determines the level of recursion to flatten.

a = [ 1, 2, [3, [4, 5] ] ]
a.flatten!   #=> [1, 2, 3, 4, 5]
a.flatten!   #=> nil
a            #=> [1, 2, 3, 4, 5]
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten!(1) #=> [1, 2, 3, [4, 5]]
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 152
def flatten!(depth=nil)
  modified = false
  ar = []
  self.each do |e|
    if e.is_a?(Array) && (depth.nil? || depth > 0)
      ar += e.flatten(depth.nil? ? nil : depth - 1)
      modified = true
    else
      ar << e
    end
  end
  if modified
    self.replace(ar)
  else
    nil
  end
end
            
inspect() click to toggle source

Private method for Array creation.

ISO 15.2.12.5.31 (x)

 
               # File mrblib/array.rb, line 91
def inspect
  return "[]" if self.size == 0
  "["+self.map{|x|x.inspect}.join(", ")+"]"
end
            
Also aliased as: to_s
map!(&block) click to toggle source

Alias for collect!

ISO 15.2.12.5.20

Alias for: collect!
reverse_each(&block) click to toggle source

for efficiency

 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 206
def reverse_each(&block)
  return to_enum :reverse_each unless block_given?

  i = self.size - 1
  while i>=0
    block.call(self[i])
    i -= 1
  end
  self
end
            
sort!(&block) click to toggle source

Sort all elements and replace self with these elements.

 
               # File mrblib/array.rb, line 210
def sort!(&block)
  self.replace(self.sort(&block))
end
            
to_s() click to toggle source

ISO 15.2.12.5.32 (x)

Alias for: inspect
uniq → new_ary click to toggle source

Returns a new array by removing duplicate values in self.

a = [ "a", "a", "b", "b", "c" ]
a.uniq   #=> ["a", "b", "c"]
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 38
def uniq
  ary = self.dup
  ary.uniq!
  ary
end
            
uniq! → ary or nil click to toggle source

Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).

a = [ "a", "a", "b", "b", "c" ]
a.uniq!   #=> ["a", "b", "c"]
b = [ "a", "b", "c" ]
b.uniq!   #=> nil
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 15
def uniq!
  ary = self.dup
  result = []
  while ary.size > 0
    result << ary.shift
    ary.delete(result.last)
  end
  if result.size == self.size
    nil
  else
    self.replace(result)
  end
end
            
ary | other_ary → new_ary click to toggle source

Set Union—Returns a new array by joining this array with other_ary, removing duplicates.

[ "a", "b", "c" ] | [ "c", "d", "a" ]
       #=> [ "a", "b", "c", "d" ]
 
               # File mrbgems/mruby-array-ext/mrblib/array.rb, line 75
def |(elem)
  raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array

  ary = self + elem
  ary.uniq! or ary
end
            

Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.

If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.

If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.

If you want to help improve the Ruby documentation, please visit Documenting-ruby.org.

blog comments powered by Disqus