Skip to content

Instantly share code, notes, and snippets.

@the-nose-knows
Created April 15, 2017 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save the-nose-knows/129c5c654b58494c31e41fc52ce90d38 to your computer and use it in GitHub Desktop.
Save the-nose-knows/129c5c654b58494c31e41fc52ce90d38 to your computer and use it in GitHub Desktop.
# Original class developed by dbjsy of StackOverflow
# User_URL: http://stackoverflow.com/users/4293919/dbjsy
# Question_URL: http://stackoverflow.com/questions/7014052/ruby-multidimensional-array
# Answer_URL: http://stackoverflow.com/a/35429385/3543437
#
# Produces a PHP/Classic-style multidimensional array.
#
# Example:
# arr = MArray.new
# arr[1][2][3] = "foo"
# => "foo"
# arr[1][2][3]
# => "foo"
class MArray < Array
def [](i)
super.nil? ? self[i] = MArray.new : super
end
end
mda = MArray.new
mda[4][4][4] = "WOW"
mda[0][0][4] = "Multi"
mda[1][0][4] = "-"
mda[2][0][4] = "Dimenstional"
mda[3][0][4] = "Array;"
mda[4][0][4] = "MArray"
puts "#{mda[0][0][4]} #{mda[1][0][4]} #{mda[2][0][4]} #{mda[3][0][4]} #{mda[4][0][4]}"
# Console Output => Multi - Dimenstional Array; MArray
puts mda[4][4][4]
# Console Output => WOW
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment