【问题标题】:How to create a 2D array of objects in Ruby?如何在 Ruby 中创建二维对象数组?
【发布时间】:2010-07-28 20:37:24
【问题描述】:

我正在为我的 roguelike 游戏创建地图,但我已经偶然发现了一个问题。我想创建一个二维对象数组。在我之前的 C++ 游戏中,我是​​这样做的:

class tile; //found in another file.

tile theMap[MAP_WIDTH][MAP_HEIGHT];

我不知道该如何使用 Ruby。

【问题讨论】:

    标签: ruby arrays object map roguelike


    【解决方案1】:
    theMap = Array.new(MAP_HEIGHT) { Array.new(MAP_WIDTH) { Tile.new } }
    

    【讨论】:

    • 谢谢。如何调用该数组中的对象函数?我需要循环遍历数组并调用每个对象 draw -function。
    • @Shub: theMap.each {|y| y.each {|x| x.draw } }
    • @Adrian 会 theMap.flatten.each {|x| x.draw} 工作(我知道它会很慢)?
    【解决方案2】:

    使用数组的数组。

    board = [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ]
    ]
    
    x = Array.new(3){|i| Array.new(3){|j| i+j}}
    

    同时查看Matrix 类:

    require 'matrix'
    Matrix.build(3,3){|i, j| i+j}
    

    【讨论】:

    • 我对多维数组和矩阵很熟悉,我的问题在于不知道如何在 ruby​​ 中将其声明为对象数组。
    • 借助动态类型,您无需在 Ruby 中进行声明。
    • 注意:Ruby >= 1.9.2 将只支持矩形矩阵。见:svn.ruby-lang.org/repos/ruby/tags/v1_9_2_rc1/NEWS
    • 我想我应该像 Adrian 向我展示的那样使用 .new() 在我的二维数组中创建一个对象。这很酷,但是我用什么来调用我没有用任何名称声明的对象?我一定很傻:(
    • 看起来像 Map.each { |i| i.每个 { |j| j.function } } 有效。将对象与数组分开是很奇怪的,至少对我来说是这样。
    【解决方案3】:

    二维数组不费吹灰之力

    array = [[1,2],[3,4],[5,6]]
     => [[1, 2], [3, 4], [5, 6]] 
    array[0][0]
     => 1 
    array.flatten
     => [1, 2, 3, 4, 5, 6] 
    array.transpose
     => [[1, 3, 5], [2, 4, 6]] 
    

    要加载 2D 数组,请尝试以下操作:

    rows, cols = 2,3
    mat = Array.new(rows) { Array.new(cols) }
    

    【讨论】:

      【解决方案4】:
      # Let's define some class
      class Foo
        # constructor
        def initialize(smthng)
          @print_me = smthng
        end
        def print
          puts @print_me
        end
      # Now let's create 2×2 array with Foo objects
      the_map = [
      [Foo.new("Dark"), Foo.new("side")],
      [Foo.new("of the"), Foo.new("spoon")] ]
      
      # Now to call one of the object's methods just do something like
      the_map[0][0].print # will print "Dark"
      the_map[1][1].print # will print "spoon"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-18
        • 2020-04-17
        • 2021-06-16
        • 1970-01-01
        • 2021-03-16
        • 1970-01-01
        • 2012-10-04
        • 1970-01-01
        相关资源
        最近更新 更多