-1

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

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
4

6 回答 6

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)]) }
于 2012-10-05T11:42:38.903 回答
0

你的第二个 else if 是错误的,random 和 if 之间必须有一个空格。

于 2012-10-05T11:53:06.563 回答
0
a= ["land", "water", "empty"]
data= (1..10).map{ a[rand(3)] }
p data
于 2012-10-05T11:54:02.460 回答
0
class Tile
  def initialize(type)
    @type = type
  end
end

types = %w(land water empty)

row = Array.new(10){ Tile.new(types.sample) }
于 2012-10-05T18:16:12.537 回答
0

单行选项:

10.times.map{ Tile.new(["land","water","empty"][rand(3)]) }
于 2012-10-05T12:13:22.623 回答
0

最新版本的 Ruby (>= 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)
于 2012-10-05T12:26:30.650 回答