Created
May 18, 2011 03:47
-
-
Save jewel12/977957 to your computer and use it in GitHub Desktop.
Arrayにインデックスを張る(define_methodについて)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def set_index( index_name, i ) | |
eval(" | |
class << self | |
define_method( '#{index_name}' ) { return self[#{i}] } | |
end | |
") | |
end | |
end | |
a1 = [1,2,3] | |
a1.set_index( 'ni', 1 ) | |
puts a1.ni | |
a2 = [1,2,3] | |
a2.ni # => no method error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment