2015-02-09 147 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指出的代码。