新手问题 怎么通过变量 去动态的取得 变量名?

MaiZardAyumi · March 24, 2017 · Last by MaiZardAyumi replied at March 24, 2017 · 2742 hits

比如我有 3 个数组,a1, a2, a3。要怎么样实现

1..3.each do |i|
   ai.each do |item|
        puts item
   end
end

,就这种动态取得变量的效果

2 Floor has deleted
Reply to Catherine

额,之前看的镐头书,ruby 基础教程,还有 codecademy 的教程,都没有提到这方面,元编程还没有看。多谢了

直接 eval 吧

a1, a2, a3 = [:a, :b], [:c, :d], [:e, :f]

(1..3).each do |i|
  binding.local_variable_get("a#{i}").each do |e|
    puts e
  end
end

(1..3).each do |i|
  eval("a#{i}").each do |e|
    puts e
  end
end
Reply to ecnelises

原来如此简单👌

MaiZardAyumi closed this topic. 24 Mar 21:50
You need to Sign in before reply, if you don't have an account, please Sign up first.