迭代器中的Ruby instance_variable_set错误:`market_0_home'不允许作为实例变量名

时间:2012-07-10 00:17:23

标签: ruby iterator block variable-assignment each

首先,这里是在下面的迭代之外的@ market_0_home的分配,只是为了告诉你我试过

>> @market_0_home = 3
=> 3

好的,那里没有错误,现在让我们在一个有点复杂的迭代中尝试这个

>> markets
=> [{"home"=>"CO", "name"=>"David Douglas"}, {"home"=>"SC", "name"=>"David Robertson"}]
>> markets.each_with_index do |market, i|
?> market.each do |name, v|
?> instance_variable_set "market_#{i}_#{name}", v
>> end
>> end
NameError: `market_0_home' is not allowed as an instance variable name
from (irb):23:in `instance_variable_set'
from (irb):23
from (irb):22:in `each'
from (irb):22
from (irb):25:in `each_with_index'
from (irb):21:in `each'
from (irb):21:in `each_with_index'
from (irb):21
>> 

1 个答案:

答案 0 :(得分:6)

我在@下面的行的变量名称中添加了instance_variable_set

@market_0_home = 3
markets = [{"home"=>"CO", "name"=>"David Douglas"}, {"home"=>"SC", "name"=>"David Robertson"}]
markets.each_with_index do |market, i|
  market.each do |name, v|
    instance_variable_set "@market_#{i}_#{name}", v
  end
end

当我运行它时,它运行正常。

=> 3
>> markets = [{"home"=>"CO", "name"=>"David Douglas"}, {"home"=>"SC", "name"=>"David Robertson"}]
=> [{"home"=>"CO", "name"=>"David Douglas"}, {"home"=>"SC", "name"=>"David Robertson"}]
>> markets.each_with_index do |market, i|
?>       market.each do |name, v|
?>           instance_variable_set "@market_#{i}_#{name}", v
>>       end
>>   end
=> [{"home"=>"CO", "name"=>"David Douglas"}, {"home"=>"SC", "name"=>"David Robertson"}]
>> @market_0_home
=> "CO"
>> @market_1_home
=> "SC"