2010-11-22 3 views
0

J'essaie ruby ​​en faisant un programme dont j'ai besoin. J'ai une classe personnalisée, et j'ai besoin d'un tableau d'objets de cette classe. Cette classe personnalisée a certains attributs qui changent au cours du programme. Comment puis-je trouver un objet spécifique dans mon tableau, pour y accéder et le modifier?Ruby tableau objet trouver

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 
+0

Comment faire vous identifiez l'objet Mathima auquel vous souhaitez ajouter quelque chose? Et quel est ce "quelque chose", est-ce le contenu de tmima? –

+0

merci à tous. J'ai utilisé un hachage pour mathimata et ça marche très bien. – pvinis

Répondre

2

Utilisez un Hash pour mathimata comme Greg a fait remarquer:

mathimata = {} 
File.read("./leit/sortedinput0.txt").lines do |line| 
    id, tmima, rest = line.split(' ', 3) 
    mathimata[id] ||= Mathima.new(id) 
end 
+1

Comme 'ids' devient plus long, cela deviendra de plus en plus lent à cause de la recherche. Un hachage serait plus rapide. –

+0

Merci! Un hachage rend le code plus simple aussi –

2
mathima = mathimata.find{|mathima| mathima.check() } 
# update your object - mathima 
0

Array.find() vous permet de rechercher de manière séquentielle à travers un réseau, mais qui n'évolue pas bien.

Je recommanderais que si vous traitez avec beaucoup d'objets ou d'éléments, et qu'ils soient uniques, alors un hachage sera beaucoup mieux. Les hashs permettent une recherche indexée basée sur leur clé.

En raison de vous ne sont en gardant des identifiants uniques, soit un ensemble ou une table de hachage serait un bon choix:

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

Set est entre tableau et une table de hachage. Il ne permet que des entrées uniques dans la collection, c'est donc comme un tableau exclusif. Il n'autorise pas les recherches/accès par une clé comme un Hash.

En outre, vous pouvez obtenir vos deux premiers mots d'une manière plus Ruby comme:

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) 

normalement écrit:

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

ou:

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