Guest User

Untitled

a guest
May 23rd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. class Thing
  2. def initialize
  3. @array = [[0, 0, 0], [1, 1, 1]]
  4. end
  5. end
  6.  
  7. thing = Thing.new
  8.  
  9. @array[0][1] # => 0
  10.  
  11. position_array = [0, 1]
  12. @array[position_array] # => 0
  13.  
  14. class Thing
  15. def [](position_array)
  16. index_row, index_col = position_array
  17. @array[index_row][index_col]
  18. end
  19.  
  20. def get_value(position_array)
  21. @array[position_array] # doesn't work
  22. # self[position_array] # does work
  23. end
  24. end
  25.  
  26. thing.get_value([0, 1])
  27. # >> 'get_value': no implicit conversion of Array into Integer (TypeError)
  28.  
  29. array.methods.grep(/[]/)
  30. # [:[], :[]=]
  31.  
  32. thing_object.methods.grep(/[/)
  33. # [:[]]
  34.  
  35. module MyArrayExtension
  36. def [] (*param)
  37. if param.size == 2
  38. row, col = param
  39. raise ArgumentError, 'Row must be an integer' if row.class != Integer
  40. raise ArgumentError, 'Column must be an integer' if col.class != Integer
  41. raise ArgumentError, "Element at row #{row} is not an array" if self[row].class != Array
  42. self[row][col]
  43. else
  44. super
  45. end
  46. end
  47. end
  48.  
  49. class Array
  50. prepend MyArrayExtension
  51. end
  52.  
  53. thing = [[1,2,3],[4,5,6]]
  54. puts "The 2D array is: #{thing}"
  55. puts "Extension used on the thing to get at element 1 of first array:"
  56. puts thing[0,1]
  57.  
  58. puts '-' * 20
  59.  
  60. normal = [1,2,:blah,4,5]
  61. puts "Normal array is #{normal}"
  62. puts "Original [] method used to get the 3rd element:"
  63. puts normal[2]
  64.  
  65. puts '-' * 20
  66. puts "Using the extension on the non-2D array:"
  67. puts normal[0,1]
  68.  
  69. The 2D array is: [[1, 2, 3], [4, 5, 6]]
  70. Extension used on the thing to get at element 1 of first array:
  71. 2
  72. --------------------
  73. Normal array is [1, 2, :blah, 4, 5]
  74. Original [] method used to get the 3rd element:
  75. blah
  76. --------------------
  77. Using the extension on the non-2D array:
  78. ./test.rb:9:in `[]': Element at row 0 is not an array (ArgumentError)
  79. from ./test.rb:35:in `<main>'
Add Comment
Please, Sign In to add comment