2015-02-09 150 views
-1

我想遍歷一個字串的數組並將它們變成一個類的實例。事情是這樣的:如何動態定義局部變量

names_array = ["jack", "james","jim"] 

names_array.each { |name| name = Person.new } 

我使用eval像(names_array.each { |name| eval(name) = Person.new }試過),但這似乎並沒有工作。無論如何在Ruby中這樣做?

編輯 上面的例子對我真正想要做的事情有點偏離,這是我的精巧代碼。

students = ["Alex","Penelope" ,"Peter","Leighton","Jacob"] 
students_hash = Hash.new {|hash, key| key = { :name => key, :scores => Array.new(5){|index| index = (1..100).to_a.sample} } } 
students.map! {|student| students_hash[student]} 

在哪裏我的問題是

students.each {|student_hash| eval(student_hash[:name].downcase) = Student.new(students_hash)} 
+2

你打算如何再次從本地變量接收學生?聽起來像[xy問題](http://meta.stackexchange.com/a/66378)給我。 – spickermann 2015-02-09 05:45:42

+0

@spickermann:他會問的下一件事是如何獲得數組/散列中的所有局部變量:) – 2015-02-09 05:52:00

+0

我第二@spickermann:你爲什麼要這樣做?你希望達到什麼目的? – 2015-02-09 05:55:49

回答

1

我不知道如果我明白你想達到的目標。我假設你想用數組中的值初始化一些對象。並以允許快速訪問的方式存儲實例。

student_names = ['Alex', 'Penelope', 'Peter', 'Leighton', 'Jacob'] 

students = student_names.each_with_object({}) do |name, hash| 
    student = Student.new(:name => name, :scores => Array.new(5) { rand(100) }) 
    hash[name.downcase] = student 
end 

當同學們都在他們的students哈希名稱的商店,你可以通過它們的名字可以收取

students['alex'] #=> returns the Student instance with the name 'Alex' 
+1

我認爲OP需要名爲'jack','james'和'jim'的變量。 – 2015-02-09 05:32:07

+0

@ muistooshort是對的我添加了一些更詳細的問題,所以你可以看到我正在試圖做什麼 – Peter 2015-02-09 05:38:45

+0

更新了我的答案... – spickermann 2015-02-09 07:16:07

0

你不能。見How to dynamically create a local variable?

紅寶石操縱使用綁定局部變量,但這裏的漁獲:只能綁定一個綁定只能操縱創建任何變量由綁定創建綁定時已經存在局部變量是可見的。

a = 1 
bind = binding # is aware of local variable a, but not b 
b = 3 

# try to change the existing local variables 
bind.local_variable_set(:a, 2) 
bind.local_variable_set(:b, 2) 
# try to create a new local variable 
bind.local_variable_set(:c, 2) 

a # 2, changed 
b # 3, unchanged 
C# NameError 
bind.local_variable_get(:c) # 2 

eval具有完全相同的行爲,當你試圖獲取/設置一個局部變量,因爲它使用引擎蓋下的結合。

您應該重新考慮一下spickerman指出的代碼。