Skip to main content

Ruby Access a Module Like an Array

·92 words·1 min
Ruby
Author
Dennis Schneider

image

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

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

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

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

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.