2012-10-05 34 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