2016-10-05 161 views
-1

所以我寫了這段代碼,它在我把學生放在課堂外並傳遞學生參數進行搜索時起作用。但是當我嘗試像這樣運行時,它說學生是未定義的。我覺得我應該使用初始化方法,但我無法弄清楚如何使用它在這種情況下Ruby對象初始化

class Student 

def search(name) 
i = 0; 

    students = [ 

    {:firstname => "John", :lastname => "LastnameJohn", :phonenumber => 123456789}, 

    {:firstname => "Ken", :lastname => "Lastnameken", :phonenumber => 456734244}, 

    {:firstname => "Marisa", :lastname => "lastnamemarisa", :phonenumber => 443234567}, 
    {:firstname => "Ken", :lastname => "Kenlastname", :phonenumber => 456734244} 
    ] 

    while i < students.length 
    if(students[i][:firstname] == name) 
     puts students[i] 
    end 
    i = i + 1; 
    end 
end 
end 

a = Student.new 
a.search("John") 

回答

0

你不應該這樣定義一個方法內部列表。要麼你應該讓他們進來,或者你應該讓他們在另一個班級或模塊中定義。

例如:

students = [ 
    {:firstname => "John", :lastname => "LastnameJohn", :phonenumber => 123456789}, 
    {:firstname => "Ken", :lastname => "Lastnameken", :phonenumber => 456734244}, 
    {:firstname => "Marisa", :lastname => "lastnamemarisa", :phonenumber => 443234567}, 
    {:firstname => "Ken", :lastname => "Kenlastname", :phonenumber => 456734244} 
] 

class Student 
    def initialize(list) 
    @list = list 
    end 

    def search(name) 
    @list.select do |student| 
     student[:firstname] == name 
    end.each do |student| 
     puts student.inspect 
    end 
    end 
end 

a = Student.new(students) 
a.search("John") 

它使用Enumerable方法select篩選出你感興趣的,而不是你原來的代碼行。

+0

,什麼是做|學生|?對不起,我剛開始學習Ruby。我很困惑 –

+0

通讀我已鏈接到的Enumerable文檔。它解釋了很多很多的例子。 'do | ... |'表示法是你如何調用一個塊,類似於JavaScript中的'function(...){}'。 – tadman

+1

塊技術起初可能非常不尋常,但它確實是大多數Ruby代碼的中堅力量。花一些時間試驗它是如何工作的以及它的侷限性。 – tadman

0

你的程序是正確的。我運行它時沒有收到任何錯誤消息。然而,由於students永遠不會改變它的價值,我將其定義爲類的常量成員:

class Student 

    STUDENTS = [ .... ] 

    def search(name) 
     .... # do something with STUDENTS 
    end 

end