Skip to content Skip to sidebar Skip to footer

I found a cool way to access a module like an array:

module Fruits
  @fruits = ["Banana", "Apple", "Melon"]

  def self::[](index)
    return @fruits[index]

  def self.list_fruits
    @fruits.each { |name| print name; puts "\n" }
      puts "Those fruits are inside!"

self:: enables you to treat the whole module like an array. You could then say Fruits0 and it would show the element at the index 0, which is “Banana”. Very handy! Instead of using self:: you could also use self.. However the former is cleaner to read in my opinion.

Leave a comment