Ruby multidimensional array

前端 未结 11 1441
春和景丽
春和景丽 2020-11-28 09:30

Maybe it\'s just my lack of abilities to find stuff here that is the problem, but I can\'t find anything about how to create multidimensional arrays in Ruby.

Could s

11条回答
  •  暖寄归人
    2020-11-28 09:53

    There are two ways to initialize multi array (size of 2). All the another answers show examples with a default value.

    Declare each of sub-array (you can do it in a runtime):

    multi = []
    multi[0] = []
    multi[1] = []
    

    or declare size of a parent array when initializing:

    multi = Array.new(2) { Array.new }
    

    Usage example:

    multi[0][0] = 'a'
    multi[0][1] = 'b'
    multi[1][0] = 'c'
    multi[1][1] = 'd'
    
    p multi # [["a", "b"], ["c", "d"]]
    p multi[1][0] # "c"
    

    So you can wrap the first way and use it like this:

    @multi = []
    def multi(x, y, value)
      @multi[x] ||= []
      @multi[x][y] = value
    end
    
    multi(0, 0, 'a')
    multi(0, 1, 'b')
    multi(1, 0, 'c')
    multi(1, 1, 'd')
    
    p @multi # [["a", "b"], ["c", "d"]]
    p @multi[1][0] # "c"
    

提交回复
热议问题