Ruby动态命名数组 [英] Ruby dynamically naming arrays

查看:68
本文介绍了Ruby动态命名数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历多个数组,并希望从名称数组中动态命名它们。像这样,用 names数组 ...

I want to iterate through a number of arrays and want to dynamically name them from an array of names. Something like this, replace name with the elements from the names array...

names=[a, b, c]
names.each{|name|
name_array1=[]
name_array2=[]
name_array[0][0].each{|i|                           
    if i>0
        name_array1.push([i])
    end
    if i<0
        name_array2.push([i])
    end
  }
}

基本上创建数组 a_array1 a_array2 a_array [0] [0] b_array1 b_array2 b_array [0] [0] c_array1 c_array2 c_array [0] [0]

basically creating the arrays a_array1, a_array2, a_array[0][0], b_array1, b_array2, b_array[0][0], c_array1, c_array2, c_array[0][0]

这甚至可能吗?

推荐答案

Ruby不支持动态局部变量名称 1

Ruby does not support dynamic local variable names1.

但是,可以使用哈希轻松表示。哈希将键映射到值,在这种情况下,键表示名称,而值是数组:

However, this can be easily represented using a Hash. A Hash maps a Key to a Value and, in this case, the Key represents a "name" and the Value is the Array:

# use Symbols for names, although Strings would work too
names = [:a, :b, :c]

# create a new hash
my_arrays = {}

# add some arrays to our hash
names.each_with_index { |name, index|
   array = [index] * (index + 1)
   my_arrays[name] = array
}

# see what we have
puts my_arrays

# access "by name"
puts my_arrays[:b]

(有很多方法可以写上面的文章而没有副作用,但这应该是一个开始。)

(There are ways to write the above without side-effects, but this should be a start.)

< sup> 1 动态实例/类变量名称是另外一个故事,但是最好暂时保留为高级主题,并且不适用于当前任务。在过去(Ruby 1.8.x)中,可以使用 eval 来更改局部变量绑定,但这绝不是一种好的方法,并且在新版本中不起作用

1 Dynamic instance/class variable names are a different story, but are best left as an "advanced topic" for now and are not applicable to the current task. In the past (Ruby 1.8.x), eval could be used to alter local variable bindings, but this was never a "good" approach and does not work in newer versions.

这篇关于Ruby动态命名数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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