如何生成常量来访问Ruby数组元素?

时间:2012-03-30 09:16:29

标签: ruby arrays constants eval

我使用数组来存储fieldvalues。为了方便地添加和访问元素,我使用常量作为元素标识符。

直到现在我这样做是这样的:

stages = ["lidnummer","aardf","prest","dt_prest","aantal","bedrag","verstrekker","foutcode"]
values = ["it","can","be","anything",0,5.3,nil,88] 
LIDNUMMER,AARDF,PREST,DT_PREST,AANTAL,BEDRAG,VERSTREKKER,FOUTCODE = 0,1,2,3,1,5,6,7
p values[AARDF] => "can"

现在我已将其自动化为:

stages = ["lidnummer","aardf","prest","dt_prest","aantal","bedrag","verstrekker","foutcode"]
values = ["it","can","be","anything",0,5.3,nil,88] 
stages.each do |c|
  eval "#{c.upcase} = #{stages.index(c)}"
end
p values[AARDF] => "can"

但是我认为有一种更好的Ruby方法可以做到这一点,也许没有评估,是否有建议?

4 个答案:

答案 0 :(得分:2)

如果你坚持按照你所描述的方式而不是使用哈希,我能想到这是最简单的:

stages.zip(values) { |stage, value| Object.const_set(stage.upcase, value) }
values[BEDRAG] #=> 5

就个人而言,我只是建立一个哈希,但你比我更了解你的要求:

Hash[stages.map(&:upcase).zip(values)]
#=> {"LIDNUMMER"=>0, "AARDF"=>1, "PREST"=>2, "DT_PREST"=>3, "AANTAL"=>4, "BEDRAG"=>5, "VERSTREKKER"=>6, "FOUTCODE"=>7}

答案 1 :(得分:1)

是的,请使用HashSymbol s。

stages = {:aardf => "aardf", :prest => "prest", ...}
stages[:aardf]

对于遗产,请使用

AARDF = :aardf

stages[AARDF]

仍然有效。

答案 2 :(得分:1)

您可能会对此感兴趣 -

stages = ["lidnummer","aardf","prest","dt_prest","aantal","bedrag","verstrekker","foutcode"]
    values = [0,1,2,3,4,5,6,7]

stages = stages.zip(values).inject({}) {|h, (k,v)| h[k.upcase]=v;h}
=> {"LIDNUMMER"=>0, "FOUTCODE"=>7, "BEDRAG"=>5, "VERSTREKKER"=>6, "AANTAL"=>4, "PREST"=>2, "AARDF"=>1, "DT_PREST"=>3}


p stages['AARDF'] #=> 1

答案 3 :(得分:0)

谢谢大家,我学到了很多。 迈克尔与他的答案最接近,但不对(值数组可以包含任何东西,通常它不是元素的顺序)。 我设法结合了这里介绍的不同技术,并提出了以下建议。

stages = ["lidnummer","aardf","prest","dt_prest","aantal","bedrag","verstrekker","foutcode"]
values = ["it","can","be","anything",0,5.3,nil,88]
stages.each_with_index{|c,i|Object::const_set(c.upcase, i)}
p values[AARDF] => "it"
p values[BEDRAG] => 5.3

如果我使用哈希,它更敏感,我会以

结束
p values[hash["AARDF"]]

不是那么顺利