arrays - Ruby: catching access to variable inside class -


I have a class that creates an incoming string in nested strand cascade For an input abcde , this will generate an [[[[[[[[[[[[[, [a, b], c], d], e] .

Now, if I use any set of top level values ​​for waterfall , then [] = (index, value) The law of my class will apply.

See the examples given below, where to see the X [0] [0] , see the examples below. Code> does not explicitly apply a class method [] = . So, is it possible to gain access within class method (or at least in a different way)?

  class MyClass attr_accessor: cascade def initialize string build_cascade string.split (//) end def build_cascade array if array.length & gt; 2 array [0] = array [0..1] array.delete_at (1) build_cascade array and @cascade = array end end def [] = (index, value) puts 'you' \ '+ value.to_s +' \ 'For \ "' index.to_s + '\' Cascade! ' Enddef [] (index) @cascade [index] and end x = mylcels.new ('ABCDFghigak') x.inspect x [0] = 5 # = & gt; You have selected '0' for '0' 5 '! X [0] [0] = 10 # = & gt; No output ~  

The problem is that you are calling [] = all the array contained in your main array.

In other words, you call [] in your class , Which you are going to return that array element, and then [] = on the normal array, which comes You do not have the block to use to block

You can apply your class to structure it by using other examples of MyClass, or you can restrict access For [] = Array can overwrite the method.

It is also worth noting that how it will be used, overwriting methods on Class like Array is usually a good Ichar is not, so you want to go to something like my first advice.


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -