在 Ruby 中以编程方式创建数组名称
我是一名菜鸟程序员,想知道如何使用另一个数组中的单词列表创建数组名称。
例如,我想采用这个数组:
array = ['fruits','veggies']
并将其转换为这样的内容:
fruits = []
veggies = []
在 Ruby 中执行此操作的最佳方法是什么?
这是我的尝试,但我惨遭失败:
variables = ['awesome', 'fantastic', 'neato']
variables.each do |e|
e = []
e << [1, 2, 3]
end
puts neato
I'm a noob programmer and am wondering how to create array names using a list of words from another array.
For example, I would like to take this array:
array = ['fruits','veggies']
and turn it into something like this:
fruits = []
veggies = []
What is the best way to do this in Ruby?
Here is my shot at it, where I failed miserably:
variables = ['awesome', 'fantastic', 'neato']
variables.each do |e|
e = []
e << [1, 2, 3]
end
puts neato
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您的数组可能包含与局部变量或方法的名称匹配的值,这就是痛苦和混乱开始的时候。
可能最好改为构建数组的哈希值:
或者,如果您没有
each_with_object
:注意带有
注入
并且您必须返回< code>h 来自块。通过这种方式,您不仅拥有数组,而且还可以通过本质上使用哈希作为小型可移植名称空间来保护您的名称空间。您可以像 Jacob Relkin 演示的那样动态创建变量,但这样做会带来麻烦。如果变量的元素最终不是字母数字,您也会遇到麻烦。
The problem is that your array might contain a value that matches the name of a local variable or method and that's when the pain and confusion starts.
Probably best to build a hash of arrays instead:
Or, if you don't have
each_with_object
:Note the argument order switch in the block with
inject
and that you have to returnh
from the block.This way you have your arrays but you also protect your namespace by, essentially, using a hash as little portable namespace. You can create variables on the fly as Jacob Relkin demonstrates but you're asking for trouble by doing it that way. You can also run into trouble if the elements of
variables
end up being non-alphanumeric.