/ / Assegnazioni di array semplici [chiuso] - rubino, array

Assegnazioni di array semplici [chiuso] - ruby, array

Sto solo cercando di creare una funzione che riempia un array di oggetti, ma qualcosa non va:

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

risposte:

4 per risposta № 1

La tua sintassi è sbagliata

    [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
}

Questo funzionerebbe.

Ma una soluzione più pulita potrebbe essere:

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

0 per risposta № 2

Il tuo secondo altro se è sbagliato, deve esserci uno spazio tra casuale e if.


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

0 per risposta № 4

Un'opzione su una riga:

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

0 per risposta № 5

Le versioni recenti di Ruby (> = 1.9.3) vengono fornite con il metodo #campione. Fa parte di schieramento. Puoi usarlo per ottenere elementi casuali dall'array senza nemmeno sapere quanto sia grande l'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 per risposta № 6
class Tile
def initialize(type)
@type = type
end
end

types = %w(land water empty)

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