Ruby/Array/Multidimensional Arrays

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Combine three arrays to create multi-dimensional array

yrs = [ 2007, 2008, 2009 ]
days = [ 31, [28, 29], 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
months = [ "Jn", "Fb", "Mr", "Ap", "Ma", "Ju", "Jl", "Au", "Sp", "Oc", "Nv", "Dc" ]
d3 = [ yrs, days, months ] # => => [[2007, 2008, 2009], [31, [28, 29], 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], ["Jn", "Fb", "Mr", "Ap", "Ma", "Ju", "Jl", "Au", "Sp", "Oc", "Nv", "Dc"]]



Convert a two-dimensional array to a hash

squares = [[1,1], [2,4], [3,9]]
results = {}
squares.each { |k,v| results[k] = v }
p results                                             # => {1=>1, 2=>4, 3=>9}
p squares.inject({}) { |h, kv| h[kv[0]] = kv[1]; h }  # => {1=>1, 2=>4, 3=>9}



flatten a multi-demensional array

d2 = [ ["January", 2007],
       ["February", 2007],
       ["March", 2007] ]
d2.flatten # => ["January", 2007, "February", 2007, "March", 2007]
p d2



Size and elements in a two-dimensional array

a = [1, 2, 3, [4, 5, 6]]
p a.size                                 # => 4
p a << a                                 # => [1, 2, 3, [4, 5, 6], [...]]
p a.size                                 # => 5
a[0]                                   # => 1
a[3]                                   # => [4, 5, 6]
a[3][0]                                # => 4
a[3].size                              # => 3
a[-2]                                  # => [4, 5, 6]
a[-1]                                  # => [1, 2, 3, [4, 5, 6], [...]]
a[a.size-1]                            # => [1, 2, 3, [4, 5, 6], [...]]
a[-1][-1]                              # => [1, 2, 3, [4, 5, 6], [...]]
a[-1][-1][-1]                          # => [1, 2, 3, [4, 5, 6], [...]]



Three dimensional array

class MyArray
  def initialize
    @store = [[[]]]
  end
  def [](a,b,c)
    if @store[a]==nil ||
       @store[a][b]==nil ||
       @store[a][b][c]==nil
      return nil
    else
      return @store[a][b][c]
    end
  end
  def []=(a,b,c,x)
    @store[a] = [[]] if @store[a]==nil
    @store[a][b] = [] if @store[a][b]==nil
    @store[a][b][c] = x
  end
end
 
x = MyArray.new
x[0,0,0] = 5
x[0,0,1] = 6
x[1,2,3] = 99
puts x[1,2,3]



transpose a multi-demensional array

d2 = [ ["January", 2007], ["February", 2007], ["March", 2007] ]
d2.transpose # => => [["January", "February", "March"], [2007, 2007, 2007]]
p d2



What is a multi-dimensional Arrays

# A multidimensional array is an array of arrays. 
# You create such an array by giving array elements that are themselves arrays. 
# This is a two-dimensional array:
d2 = [ ["January", 2007],
       ["February", 2007],
       ["March", 2007] ]
 
# The array d2"s elements are also arrays.