Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created September 30, 2011 09:07
Show Gist options
  • Select an option

  • Save pasberth/1253180 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1253180 to your computer and use it in GitHub Desktop.
2次元配列を楽に作りたくて作った
class Array
alias defarray_original_at []
alias defarray_original_initialize initialize
def initialize *args, &blk
return defarray_original_initialize(*args, &blk) unless args.empty?
@default_handler = blk
end
def [] number
defarray_original_at(number) || (@default_handler && @default_handler.call(self, number))
end
end
_2d = Array.new { |ary, n| ary[n] = [] }
_2d[0] << 1
_2d[1] << 2
p _2d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment