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 initi开发者_开发知识库alize(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
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
mathima = mathimata.find{|mathima| mathima.check() }
# update your object - mathima
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]
精彩评论