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
Post a Comment