0

I am trying out ruby by making a program i need. I have a custom class, and I need an array of objects of that class. This custom class has some attributes that change in the course of the program. How can I find a specific object in my array, so I can access it and change it?

class Mathima
  attr_accessor :id, :tmimata

  def initialize(id)
    @id = id
    @tmimata = []
  end
end


# main
mathimata = []

previd = id = ""
File.read("./leit/sortedinput0.txt").lines do |line|
  array = line.split(' ')          # i am reading a sorted file
  id = array.delete_at(0)          # i get the first two words as the id and tmima
  tmima = array.delete_at(0)

  if previd != id
    mathimata.push(Mathima.new(id))  # if it's a new id, add it
  end

  # here is the part I have to go in mathimata array and add something in the tmimata array in an object. 

  previd = id
end
2
  • How do you identify which Mathima object you want to add something to? And what is that "something", is it the contents of tmima? Commented Nov 22, 2010 at 13:43
  • thank you all. I used a hash for mathimata and it's working just fine. Commented Nov 24, 2010 at 7:09

3 Answers 3

2

Use a Hash for mathimata as Greg pointed out:

mathimata = {}
File.read("./leit/sortedinput0.txt").lines do |line|
  id, tmima, rest = line.split(' ', 3)
  mathimata[id] ||= Mathima.new(id)
end
Sign up to request clarification or add additional context in comments.

1 Comment

As ids gets longer this will get slower and slower because of the lookup. A Hash would be faster.
2
mathima = mathimata.find{|mathima| mathima.check() }
# update your object - mathima

Comments

0

Array.find() lets you search sequentially through an array, but that doesn't scale well.

I'd recommend that if you are dealing with a lot of objects or elements, and they're unique, then a Hash will be much better. Hashes allow indexed lookup based on their key.

Because of you are only keeping unique IDs either a Set or a Hash would be a good choice:

mathimata.push(Mathima.new(id))  # if it's a new id, add it

Set is between Array and a Hash. It only allows unique entries in the collection, so it's like an exclusive Array. It doesn't allow lookups/accesses by a key like a Hash.

Also, you can get your first two words in a more Ruby-like way:

array = line.split(' ')          # i am reading a sorted file
id = array.delete_at(0)          # i get the first two words as the id and tmima
tmima = array.delete_at(0)

would normally be written:

id, tmima = line.split(' ')[0, 2]

or:

id, tmima = line.split(' ')[0 .. 1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.