Ruby 如何动态定义局部变量

Ruby 如何动态定义局部变量,ruby,metaprogramming,local-variables,Ruby,Metaprogramming,Local Variables,我想循环遍历一个由单字字符串组成的数组,并将它们转换为类的实例。大概是这样的: names_array = ["jack", "james","jim"] names_array.each { |name| name = Person.new } 我尝试过使用eval,比如(names|u array.each{| name | eval(name)=Person.new}),但这似乎不起作用。在Ruby中有这样做的方法吗 编辑 前面的例子有点偏离了我真正想做的是我的精确代码 student

我想循环遍历一个由单字字符串组成的数组,并将它们转换为类的实例。大概是这样的:

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

names_array.each { |name| name = Person.new }
我尝试过使用eval,比如
(names|u 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)}

我不确定我是否理解你想要实现的目标。我假设您希望使用数组中的值初始化某些对象。并以允许快速访问的方式存储实例

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'
你不能。看

Ruby使用绑定来操纵局部变量,但这里有一个问题:绑定只能操纵在创建绑定时已经存在的局部变量,并且由绑定创建的任何变量只对绑定可见

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
在尝试获取/设置局部变量时具有完全相同的行为,因为它在引擎盖下使用绑定


你应该按照斯皮克曼指出的思路重新思考你的代码。

我认为OP需要名为
jack
james
、和
jim
@muistooshort的变量。我为问题添加了更多的细节,这样你就可以清楚地看到我想要更新我的答案的内容了……谢谢大家的帮助!我将尝试这样的方法,您打算如何再次接收来自局部变量的学生?对我来说,听起来像是个难题。@spickermann:接下来他要问的是如何获取数组中的所有局部变量/hash:)我支持@spickermann:为什么要这样做?您希望实现什么?我的意思是,如果您的输入是动态的(数组),那么将其转换为局部变量是人类已知的最糟糕的数据转换。我想不出比这更不舒服的了。我不太清楚你的意思@spickermann?如果您指的是我的最后一行,以及我将如何访问新的本地定义的学生实例,我是否可以创建一个预定义的数组来将它们放入其中?也许指出我有缺陷的逻辑比屈尊的评论更有帮助