开发者

writing custom methods with def

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(m开发者_JS百科aze)

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 methodjoin' for "#":String (NoMethodError)

made it too next step

C:\test.rb:20:in each' C:\test.rb:20:inprint_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


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.


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)


join works on arrays, not on strings


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜