Forum: Ruby How to find a single cell in a 2D array?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A4b6d4278864f1e45c73ca1b3cdf743f?d=identicon&s=25 Charles Way (charles_w)
on 2016-11-30 17:59
I have defined a method to read any one of multiple maze files.

maze = []
def maze_reader
  mz_file = File.open("maze1.mz")
  while ! mz_file.eof?
    line = mz_file.gets.chomp.split(" ")
    maze << line
  end
mz_file.close

Next I need to create a method to find specific letters in the maze, say
S for start and F for finish.

I have listened to tutorials; however, I have a learning problem that
often prevents me from memorizing spoken words, and the book I am using
does not appear to cover this yet.
Is there anyone who can point me in the right direction?
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2016-12-04 11:25
This will find the first matching location in a 2D array of Strings.

maze = [['S',' ',' '],[' ',' ',' '],[' ',' ','F']]

def find_location( maze, location )
  # Go through each row
  maze.each_index do |i|
    # Find the location in the row
    result = maze[i].index( location )
    # Return the row index and location index if found
    return [i, result] if result
  end
  # return nil if nothing was found
  return nil
end

find_location maze, 'S'
=> [0, 0]
find_location maze, 'F'
=> [2, 2]
B078cb4f4fb473c7a54d1fc36d10c70e?d=identicon&s=25 Regis d'Aubarede (raubarede)
on 2016-12-05 15:31
class Array
  def rfind(sae,aa=[])
    each_with_index() { |a,i|
      r= a.kind_of?(Array) ? a.rfind(sae,aa+[i]) : a==sae ? aa+[i] :
false
      return r if r
    }
    nil
  end
end

a=[1,2,3,4]
p a.rfind(3)
p a.rfind(9)


a=[
[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,9,3,4],
[1,2,3,4],
]
p a.rfind(9)

a=[
[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],],
[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],],
[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],],
[[1,2,3,4],[1,2,3,4],[1,2,9,4],[1,2,3,4],[1,2,3,4],],
]
p a.rfind(9)

==
[2]
nil
[3, 1]
[3, 2, 2]
This topic is locked and can not be replied to.