Any experts in Ruby Class out there?
Posted: Sun Oct 13, 2024 1:40 pm
Hello all, and thanks in advance for any help! I've been trying to set up a Ruby Class that can handle and use its own internal arrays. I'm quite a novice at Ruby classes, and the nearest I've got is this:
class Destination
attr_accessor :l
@@letters
def initialize(l)
@l=l
end
### # out if clauses on first run...
@@letters=[] if @@letters==nil
def name
@@letters.collect{|ch| ch[0]}.join
end
def addLet(l)
@@letters << l
end
def wipe
@@letters.clear
end
end
I need in the class an array, @@letters (I'll eventually need other ones too). Line 3 sets up a variable called @@letters. LIne 7 turns it into an empty array. The ... if @@letters==nil... is to keep already inserted members of the array, but without line 3 it throws up an "uninitialised class variable" error - I have to run the class with the if statement #'ed out first time. Once that's done it works!
With the class now running I can do things like
@ylist=Destination.new("") a new instance of a Destination
%w[W A S H I N G T O N].each{|l| @ylist.addLet(l)} ... each letter becomes a member of @@letters
@ylist.name produces 'WASHINGTON'
It needs to be individual letters because I want to set up and access other data related to each letter. I'm sure there must be a better way to handle this, but so far it's eluded me.
class Destination
attr_accessor :l
@@letters
def initialize(l)
@l=l
end
### # out if clauses on first run...
@@letters=[] if @@letters==nil
def name
@@letters.collect{|ch| ch[0]}.join
end
def addLet(l)
@@letters << l
end
def wipe
@@letters.clear
end
end
I need in the class an array, @@letters (I'll eventually need other ones too). Line 3 sets up a variable called @@letters. LIne 7 turns it into an empty array. The ... if @@letters==nil... is to keep already inserted members of the array, but without line 3 it throws up an "uninitialised class variable" error - I have to run the class with the if statement #'ed out first time. Once that's done it works!
With the class now running I can do things like
@ylist=Destination.new("") a new instance of a Destination
%w[W A S H I N G T O N].each{|l| @ylist.addLet(l)} ... each letter becomes a member of @@letters
@ylist.name produces 'WASHINGTON'
It needs to be individual letters because I want to set up and access other data related to each letter. I'm sure there must be a better way to handle this, but so far it's eluded me.