Forum: Ruby Grabbing an integer out of an array

566c379bb261d7da967c84dee22fb487?d=identicon&s=25 Austin S. (austin_s)
on 2013-10-27 23:07
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.
3df767279ce7d81db0a5bb30f5136863?d=identicon&s=25 Matthew Kerwin (mattyk)
on 2013-10-27 23:18
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.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.