Python style list comprehension

Trying to write Python code in Ruby but no luck with nested lists. Here is the Python code:

class Tile:
def init(self, block_path)
self.block_path = block_path

def map():
new_map = [ [ Tile(False) for y in range(0, 30) ] for x in range(0, 30) ]

  new_map[10][10].block_path = True
  new_map[20][20].block_path = True

  return new_map

Here is the Ruby code but is doesn’t work:

class Tile
attr_accessor :blocks_path
def initialize(blocks_path)
@blocks_path = blocks_path

def map()
new_map = [[for j in 0…29 do j end], for i in 0…29 do end]

   new_map[10][10].blocks_path = true
   new_map[20][20].blocks_path = true

  return new_map


Please help

You can make multi-dimensional arrays directly, using blocks:

2.7.2 :002 > table = {}
 => [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil,... 
2.7.2 :003 > table[0][1] = "a"
 => "a" 
2.7.2 :004 > table
 => [[nil, "a", nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]] 

To make a new tile at each position, add that as a block to the second call. Does this do what you want for new_map:

new_map = { {}}

Ideally I want to reproduce this.

Ideally I want to reproduce this.

OK, but where are you getting stuck? I showed you an equivalent statement for making new_map.

Ranges in Ruby are not so different to Python, just count the dots:

for x in (0...30)
   # etc

I get errors when trying to call the map: map_to_draw[x][y].block_path == True:

what is True ?
If you want the boolean true value, you want true, like you wrote in your first post.

(NB: Python True/False vs Ruby true/false!)

That is what I meant ‘true’, Python code creeping in.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs