i'm completely new to Ruby and programming in general.
To initialise a class instance I would do the following:
ben_smith = Client.new("Ben Smith")
As needed I would call the instance reference (not sure if 'reference' is the correct term):
ben_smith
=> #<Client:0x007fca2f630de8 @name="Ben Smith">
I'm currently learning about Has-Many object relationships and have written a method to allow a class instance of class "Freelancer" to create another class instance of class "Client".
The issue is the Client instances are created but I don't know how to access them independent of the "freelancer_1" instance.
class Client
attr_accessor :name, :company, :freelancer
def initialize(name, company)
@name = name
@company = company
end
end
class Freelancer
attr_accessor :name, :skill, :years_of_experience
def initialize(name, skill, years_of_experience)
@name = name
@years_of_experience = years_of_experience
@skill = skill
@clients = []
end
def add_client_by_name(name, company)
client = Client.new(name, company)
@clients << client
client.freelancer = self
end
def clients
@clients
end
end
Here's my seed code:
freelancer_1 = Freelancer.new("Bobby", "Plumber", 10)
freelancer_1.add_client_by_name("Howard Rose", "TNP")
freelancer_1.add_client_by_name("Antony Adel", "Realmless")
freelancer_1.add_client_by_name("Luke Tiller", "SKY")
I'd like to access the "clients" like so:
luke_tiller.company
But there is seemly no "luke_tiller" reference available. I can access clients via freelancer_1:
freelancer_1.clients[2]
I'm really unsure
Apologies for the basic questions and my rather long post. Thank you in advance any help given.
Instead of index-based access, you could add a new method in the Freelancer class like:
class Freelancer
def find_client_by_name(name)
@clients.find { |client| client.name == name }
end
end
Now you could do:
luke_tiller = freelancer_1.find_client_by_name('Luke Tiller')
puts luke_tiller.company
# SKY
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With