Create two-dimensional arrays and access sub-arrays in Ruby

前端 未结 9 882
走了就别回头了
走了就别回头了 2020-11-28 03:26

I wonder if there\'s a possibility to create a two dimensional array and to quickly access any horizontal or vertical sub array in it?

I believe we can access a hor

相关标签:
9条回答
  • 2020-11-28 04:07

    You didn't state your actual goal, but maybe this can help:

    require 'matrix'  # bundled with Ruby
    m = Matrix[
     [1, 2, 3],
     [4, 5, 6]
    ]
    
    m.column(0) # ==> Vector[1, 4]
    

    (and Vectors acts like arrays)

    or, using a similar notation as you desire:

    m.minor(0..1, 2..2) # => Matrix[[3], [6]]
    
    0 讨论(0)
  • 2020-11-28 04:09
    a = Array.new(Array.new(4))
    
    0.upto(a.length-1) do |i|
      0.upto(a.length-1) do |j|
        a[i[j]] = 1
      end
    end
    
    0.upto(a.length-1) do |i|
      0.upto(a.length-1) do |j|
        print a[i[j]] = 1 #It's not a[i][j], but a[i[j]]
      end
      puts "\n"
    end
    
    0 讨论(0)
  • 2020-11-28 04:13

    I'm quite sure this can be very simple

    2.0.0p247 :032 > list = Array.new(5)
    
     => [nil, nil, nil, nil, nil] 
    
    2.0.0p247 :033 > list.map!{ |x| x = [0] }
    
     => [[0], [0], [0], [0], [0]] 
    
    2.0.0p247 :034 > list[0][0]
    
      => 0
    
    0 讨论(0)
提交回复
热议问题