在Ruby中动态创建局部变量 [英] Dynamically creating local variables in Ruby

查看:85
本文介绍了在Ruby中动态创建局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,正在解析该文件并将其插入数据库中。我想写一个解析器,考虑到列顺序将来可能会改变的事实。

I have a CSV file which I'm parsing and inserting bits of it in a database. I'd like to write a parser which takes account of the fact that the column order may change in the future.

我认为我可以通过抓住标题来实现行作为数组,对于每一行,将值放入动态创建的局部变量中(使用eval)。但是,这似乎不起作用,因为在eval之外似乎无法访问局部变量。我在其他地方读过,这在ruby 1.9中可能是正确的,但我使用的是1.8.7

I thought that I could do this by grabbing the header line as an array, and for each line, putting the value in a dynamically created local variable (using eval). However this doesn't seem to work, as local variables don't seem to be accessible outside the eval. I've read elsewhere that this may be correct in ruby 1.9, but I'm using 1.8.7

代码,例如:

headers = ["a", "b"]
  headers.each do |h|
  p e_str = h+"=1"
  eval(e_str)
end
puts a

根本不起作用,给出


test.rb:6:未定义的局部变量或
方法'a'用于main:Object(NameError)

test.rb:6: undefined local variable or method `a' for main:Object (NameError)

尽管第3行显示 a = 1和 b = 1

though line 3 prints "a=1" and "b=1" as expected

有人知道我该怎么做吗?

Does anyone know how I could go about this?

推荐答案

使用openstruct可以获得类似的效果

You can get a similar effect using an openstruct

require 'ostruct'

x = OpenStruct.new

headers = ["a", "b"]
headers.each do |h|
  x.send("#{h}=", 1)
end
puts x.a
puts x.b

这篇关于在Ruby中动态创建局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆