2012-10-05 33 views
-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

你的语法是错误的

[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)]) } 
+0

所以 “<<” 将对象添加到阵列?我可以直接在数组上使用rand? –

+0

是的,'<<'是一个重载操作符,基本上是'push'的语法糖。我们没有在数组上使用rand,而是只使用了结果,rand(x..y)返回一个数字,我们用它作为索引来获取数组'types'的相应项。 – Need4Steed

0

你的第二否则,如果是错误的,必须有随机的,如果之间的空间。

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

甲一个行选项:

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

最近红宝石(> = 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) 
0
class Tile 
    def initialize(type) 
    @type = type 
    end 
end 

types = %w(land water empty) 

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

@Emil 2空格缩进是[标准的红宝石](http://stackoverflow.com/questions/2678817/2-spaces-or-1-tab-whats-the-standard-for-indentation-in-the-rails -社区)。 – steenslag

+0

哎呀,对不起! :) – Emil