Ruby implementing access to members of collection by [] -


is there way implement access member of collection []. mean have program linked list , wanna access members coll[int]. there way that?

is linked list own class? if so, can define [] method class:

class linkedlist    ...    def [](int index)     node = @head     index.times       node = node.next     end     node   end  end 

this code presumes member variable @head references first entry in list, , method #next returns next entry in list. assumes zero-based indexing, , has no error handling index being out of range.

in use, call way want:

linked_list[2] 

ruby treats though had written:

linked_list.[](2) 

these 2 syntaxes equivalent, 1 writes first, shorter form.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -