gpt4 book ai didi

迭代器 : `market_0_home' is not allowed as an instance variable name 内部的 Ruby instance_variable_set 错误

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:44 26 4
gpt4 key购买 nike

首先,这是在下面的迭代之外对@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
>>

最佳答案

我在下面的 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"

关于迭代器 : `market_0_home' is not allowed as an instance variable name 内部的 Ruby instance_variable_set 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11405030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com