tags:

views:

63

answers:

4

Warning Rookie/newb mistakes contained within read at your own risk!

Ok trying to put together some code to read and print a text based maze file. This is what I have so far:

def read_maze( filename )
local_maze = []
mz_file = File.open(filename,"r")

while ! mz_file.eof? do
line = mz_file.gets.chomp
local_maze = line.scan(/./)
end

mz_file.close
return local_maze
end
puts "done"

maze = read_maze("maze1.mz")

def print_maze( maze )
maze.each {|row|
puts row.join("")
 }
end
puts "made it too next step"
print_maze(maze)

here's my maze1.mz file representation called from another file

  ########
  #  F   #
  ####   #                          
  #  S   #                         
  ########

I'm getting method errors inside my custom defs here's what netbeans spits back

done quick note: I edited my C:\ errors to not list my directoy structure on hard drive

C:\test.rb:21:in print_maze': undefined method join' for "#":String (NoMethodError)

made it too next step

C:\test.rb:20:in each' C:\test.rb:20:in print_maze' C:\test.rb:25

I've been looking at this for about 2 hours and haven't been able to resolve the # issue irb is not helping either

A: 

join works on arrays, not on strings

ennuikiller
+1  A: 

Change the line

local_maze = line.scan(/./)

to

local_maze << line.scan(/./)

and you will get the maze printed out. << adds items to an array.

Jonas Elfström
+1  A: 

How do you want the output of read_maze()?

If you want an array containing every character you need to use local_maze.concat(line.scan(/./))

If you want an array of arrays, each containing every char on a given row then you need to use local_maze << line.scan(/./)

By your print_maze() I guess you want the last one, in that case try something simpler like:

def read_maze(filename)
  File.open(filename) do |f|
   f.collect { |line| line.chomp.scan(/./) }
  end
end

def print_maze(m)
 m.each { |row| puts row.join("") } 
end

maze = read_maze("maze1.mz")
print_maze(maze)
Miguel Fonseca
Thanks for the help went to http://ruby-doc.org/core/classes/Array.html#M002167 about the join and << issue Thanks for the corrections. I appreciate them much!
Matt
A: 

you can also replace line.chomp.scan(/./) with line.chomp.to_a - its more clearly and effectively

aaz