简单阵列分配

时间:2012-10-05 11:36:31

标签: ruby arrays

我只是想创建一个用对象填充数组的函数,但是出了点问题:

row1 = []

class Tile
    def initialize(type)
        @type = type
    end
end

def FillRow1

    [1..10].each {
        random = rand(1..3)
        if random == 1 row1.(Tile.new("land") end 
        else if random == 2 row1.(Tile.new("Water") end
        else ifrandom == 3 row1.(Tile.new("empty") end
    }
    row1
end

6 个答案:

答案 0 :(得分:4)

您的语法错误

    [1..10].each {
        random = rand(1..3)
        if random == 1 then row1.push(Tile.new("land")) end 
        else if random == 2 then row1.push(Tile.new("Water")) end
        else ifrandom == 3 then row1.push(Tile.new("empty") end
    }

这样可行。

但更清洁的解决方案可能是:

types = ["Land","Water","Empty"]
10.times{ row1 << Tile.new(types[rand(0..2)]) }

答案 1 :(得分:0)

如果你的第二个错误,那么随机和if之间必须有一个空格。

答案 2 :(得分:0)

a= ["land", "water", "empty"]
data= (1..10).map{ a[rand(3)] }
p data

答案 3 :(得分:0)

单行选项:

10.times.map{ Tile.new(["land","water","empty"][rand(3)]) }

答案 4 :(得分:0)

Ruby的最新版本(&gt; = 1.9.3)附带方法#sample。它是Array的一部分。您可以使用它来从数组中获取随机元素,甚至不知道数组甚至是多大。

class Tile
    TILE_TYPES = %w(land water empty)

    def initialize(type)
        @type = type
    end

    def to_s
        "Tile of type: #{@type}"
    end
end

# Generate 10 tiles
rows = (1..10).map do 
    Tile.new Tile::TILE_TYPES.sample
end

puts rows
#=> Tile of type: empty
#   Tile of type: land
#   ...

# If you want to pick more then 1 random element you can also do
puts Tile::TILE_TYPES.sample(3)

答案 5 :(得分:0)

class Tile
  def initialize(type)
    @type = type
  end
end

types = %w(land water empty)

row = Array.new(10){ Tile.new(types.sample) }