-1

I am just trying to make a function that fills an array with objects, but something is wrong:

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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303

6 Answers6

4

Your syntax is wrong

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

This would work.

But a cleaner solution may be:

types = ["Land","Water","Empty"]
10.times{ row1 << Tile.new(types[rand(0..2)]) }
Need4Steed
  • 2,170
  • 3
  • 22
  • 30
  • so "<<" adds the object to the array? And I can use rand directly on arrays? – Борис Цейтлин Oct 05 '12 at 11:59
  • Yes, `<<` is an overloaded operator, basically a syntax sugar for `push`. And we're not using rand on an array, instead, we only used the result, rand(x..y) returns a number, which we used as the index to fetch the corresponding item of the array `types`. – Need4Steed Oct 05 '12 at 12:12
0

Your second else if is wrong, there must be a space between random and the if.

0
a= ["land", "water", "empty"]
data= (1..10).map{ a[rand(3)] }
p data
nurettin
  • 11,090
  • 5
  • 65
  • 85
0

A one-line option:

10.times.map{ Tile.new(["land","water","empty"][rand(3)]) }
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
0

Recent versions of Ruby (>= 1.9.3) come with method #sample. It is part of Array. You can use it to get random element(s) from array without even knowing how big array even is.

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)
Oto Brglez
  • 4,113
  • 1
  • 26
  • 33
0
class Tile
  def initialize(type)
    @type = type
  end
end

types = %w(land water empty)

row = Array.new(10){ Tile.new(types.sample) }
Emil
  • 7,220
  • 17
  • 76
  • 135
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • @Emil 2 spaces indentation is [standard in ruby](http://stackoverflow.com/questions/2678817/2-spaces-or-1-tab-whats-the-standard-for-indentation-in-the-rails-community). – steenslag Oct 05 '12 at 19:13