Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Thing
- def initialize
- @array = [[0, 0, 0], [1, 1, 1]]
- end
- end
- thing = Thing.new
- @array[0][1] # => 0
- position_array = [0, 1]
- @array[position_array] # => 0
- class Thing
- def [](position_array)
- index_row, index_col = position_array
- @array[index_row][index_col]
- end
- def get_value(position_array)
- @array[position_array] # doesn't work
- # self[position_array] # does work
- end
- end
- thing.get_value([0, 1])
- # >> 'get_value': no implicit conversion of Array into Integer (TypeError)
- array.methods.grep(/[]/)
- # [:[], :[]=]
- thing_object.methods.grep(/[/)
- # [:[]]
- module MyArrayExtension
- def [] (*param)
- if param.size == 2
- row, col = param
- raise ArgumentError, 'Row must be an integer' if row.class != Integer
- raise ArgumentError, 'Column must be an integer' if col.class != Integer
- raise ArgumentError, "Element at row #{row} is not an array" if self[row].class != Array
- self[row][col]
- else
- super
- end
- end
- end
- class Array
- prepend MyArrayExtension
- end
- thing = [[1,2,3],[4,5,6]]
- puts "The 2D array is: #{thing}"
- puts "Extension used on the thing to get at element 1 of first array:"
- puts thing[0,1]
- puts '-' * 20
- normal = [1,2,:blah,4,5]
- puts "Normal array is #{normal}"
- puts "Original [] method used to get the 3rd element:"
- puts normal[2]
- puts '-' * 20
- puts "Using the extension on the non-2D array:"
- puts normal[0,1]
- The 2D array is: [[1, 2, 3], [4, 5, 6]]
- Extension used on the thing to get at element 1 of first array:
- 2
- --------------------
- Normal array is [1, 2, :blah, 4, 5]
- Original [] method used to get the 3rd element:
- blah
- --------------------
- Using the extension on the non-2D array:
- ./test.rb:9:in `[]': Element at row 0 is not an array (ArgumentError)
- from ./test.rb:35:in `<main>'
Add Comment
Please, Sign In to add comment