While there are plenty of places on the web that talk about Ruby Arrays and Ruby Classes, I never have found one that just explained how to use a Class as an Array. So I thought I would post one for those who might want something simple to reference
First, the sample code:
class Test
@dd = Array.new
def initialize
@dd = loadArray()
end
def [](a)
@dd[a]
end
def []=(a, b)
@dd[a] = b
end
def list
@dd.each do |i|
puts i
end
end
def sort
aa = Array.new
aa = @dd.sort
@dd = aa
end
private
def loadArray
rr = Array.new
rr << "one"
rr << "two"
rr << "three"
rr << "four"
return rr
end
end
The class defines an internal array (@dd) and when you initialize an instance of Class Test, it will call the private method ‘loadArray’ to put some values into the array. Since this is just an example, we are just putting some dummy data in the array. Your class may not even have a ‘loadArray’ method if you don’t need to pre-load the array with values. Lots of time, I will be loading in the contents of a file when I initialize the Class.
irb(main):177:0> g = Test.new => #<Test:0x2cf400c @dd=["one", "two", "three", "four"]>
So now our Test object exists with values in the array. But how do we get at them? Easy! The ‘[](a)’ method allows for access to the array elements like so:
irb(main):178:0> g[3] => "four" irb(main):179:0> g[4] => nil
If we need to assign a value, the ‘[]=(a,b)’ method does this:
irb(main):180:0> g[4] = "five" => "five" irb(main):181:0> g => #<Test:0x2cf400c @dd=["one", "two", "three", "four", "five"]>
The real beauty of having your array as part of a Class is that you can create custom methods to act against the array:
irb(main):182:0> g.list one two three four five => ["one", "two", "three", "four", "five"] irb(main):183:0> g.sort => ["five", "four", "one", "three", "two"]
Of course you can’t call the ‘loadArray’ method outside of the class:
irb(main):184:0> g.loadArray
NoMethodError: private method `loadArray' called for #<Test:0x2cf400c @dd=["five", "four", "one", "three", "two"]>
from (irb):184
from :0
Here’s a working example from my toolkit:
class Ignore
@ignores = Array.new
def initialize(ignListFile)
@ignores = _loadIgnoreList(ignListFile)
end
def check(value)
@ignores.each do |j|
if value[/#{j}/]
return true
end
end
return false
end
def list
@ignores.each do |l|
puts l
end
end
def [](a)
@ignores[a]
end
def []=(a,b)
@ignores[a] = b
end
###-----------###
private
###-----------###
def _loadIgnoreList(ifile)
rr = Array.new
begin
f = File.read(ifile)
rescue
raise "Error! Unable to open Ignore list file: #{ifile}."
end
rr = YAML.load(f)
return rr
end
end
The Ignore Class stores a list of strings to ignore when scanning through files/lists/values/etc. Its used like so:
ign = Ignore.new("list_to_ignore.yml")
...
list.each do |test|
if not ign.check(test)
# work with the item
else
# ignored
end
end






