We now check if the book titles are deleted from the first and end of the list which should give us ‘nil’ when and if the list becomes void of contents.
list.deleteFirst >> Books: ABDC–Author1 (1)
list.deleteFirst >> Books: EFGH–Author2 (2)
list.deleteLast >> Books: MNOP–Author1 (1)
list.deleteLast >> Books: IJKL–Author3 (3)
list.deleteLast >> nil
We now include the use of the square brackets which allows us to acces the specific elements by the index instead of having to define each item specifically.
class BookList
def[](key)
if key.kind_of?(Integer)
@Books[key]
else
# …
end
end
end
Testing the code is also very straightforward:
list[0] >> Books: ABCD — Author1 (1)
list[2] >> Books: IJKL — Author (3)
list[9] >> nil
The next posts will add more functions and operators to further simplify our code making it shorter and making you more familiar with the syntax of Ruby.
