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

bou*_*uby 1 ruby each iterator block variable-assignment

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

>> @market_0_home = 3
=> 3
Run Code Online (Sandbox Code Playgroud)

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

>> 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
>> 
Run Code Online (Sandbox Code Playgroud)

Kev*_*ell 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
Run Code Online (Sandbox Code Playgroud)

当我运行它,它工作正常.

=> 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"
Run Code Online (Sandbox Code Playgroud)