Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a class instance reference name?

Tags:

object

ruby

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

  1. if it possible to assign and make available named unique references (client_1, client_2, client_3 etc) using the add_client_by_name method?
  2. Is there a way to easily access the Client Instance directly?
  3. Why are instance 'references' seemly hidden for both examples given? For the first example, I can call ben_smith but there is mention of this reference if we call ben_smith.

Apologies for the basic questions and my rather long post. Thank you in advance any help given.

like image 632
jolee Avatar asked Nov 17 '25 06:11

jolee


1 Answers

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
like image 104
Lenin Raj Rajasekaran Avatar answered Nov 20 '25 08:11

Lenin Raj Rajasekaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!