Grabbing an integer out of an array

class List
@contacts = []
@id = 1000

def self.add_contact(contact)
contact.id = @id
@contacts << contact
@id += 1
end

So I have an id that gets attached to the contact with each entry to the
array. Now i want to be able to locate a specific entry using the id’s
as the identifier. I am new to ruby so any help is appreciated, thanks.

Austin S. wrote in post #1125813:

class List
@contacts = []
@id = 1000

def self.add_contact(contact)
contact.id = @id
@contacts << contact
@id += 1
end

So I have an id that gets attached to the contact with each entry to the
array. Now i want to be able to locate a specific entry using the id’s
as the identifier. I am new to ruby so any help is appreciated, thanks.

The easiest way would be:

def self.find_contact(contact_id)
  @contacts.find{|c| c.id == contact_id }
end

The documentation for the `find’ method is here
http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-find

However that’s a linear search over the array for each lookup. An
alternative might be something like this:

class List
@contacts = {} # Hash, not array
@id = 1000

def self.add_contact(contact)
  contact.id = @id
  @contacts[@id] = contact
  @id += 1
end

def self.find_contact(contact_id)
  @contacts[contact_id]
end

Both of these mechanisms return `nil’ if no such contact is found.

As a final question: why do you define the methods on `self’? The
combination of class methods and instance variables (@id, @contacts) is
a bit odd.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs