我可以声明一个数组,其中数组元素之一是未声明的变量吗? (红宝石)
#input_from_the_net = ""
my_array = [ ["Header name" , input_from_the_net] ]
input_from_the_net = "a value scraped from the net"
puts "#{my_array[0][0]} is #{my_array[0][1]}"
编辑:
我稍后在循环中使用变量 input_from_the_net
并将其值分配给哈希值。然后将该哈希值存储在另一个哈希值中。如果我使用 input_from_the_net.replace("a value scraped from the net") 它将替换所有哈希中的值。这是不希望的。我希望所有哈希值都保持正确的值。
EDIT2:更详细的示例代码
`require 'pp'
input_from_the_net = ""
def parse_the_website()
(0..5).each { |index|
input_from_the_net = index+23
@my_hash[index] = {@my_array[0][0] => input_from_the_net}
}
end
@my_array = [ ["Header name" , input_from_the_net] ]
#my_array is used on different places of the code
@my_hash = {}
parse_the_website
pp @my_hash
Q1:我可以让这个工作而不改变行的顺序吗?
Q2:如果我取消注释 #input_from_the_net = ""
,则打印时变量 input_from_the_net 的值是“”而不是“从网络中抓取的值”。怎么会?
#input_from_the_net = ""
my_array = [ ["Header name" , input_from_the_net] ]
input_from_the_net = "a value scraped from the net"
puts "#{my_array[0][0]} is #{my_array[0][1]}"
EDIT:
I use the variable input_from_the_net
later on in the loop and assign its value into a hash. That hash is then stored inside another hash. If I use input_from_the_net.replace("a value scraped from the net")
it replaces the value inside all hashes. That is not desired. I want all hashes to keep the correct values.
EDIT2: more detailed sample code
`require 'pp'
input_from_the_net = ""
def parse_the_website()
(0..5).each { |index|
input_from_the_net = index+23
@my_hash[index] = {@my_array[0][0] => input_from_the_net}
}
end
@my_array = [ ["Header name" , input_from_the_net] ]
#my_array is used on different places of the code
@my_hash = {}
parse_the_website
pp @my_hash
Q1: can I make this work and not change the order of lines?
Q2: if I uncomment #input_from_the_net = ""
the value of the variable input_from_the_net at the time of printing is "" not the "a value scraped from the net". How come?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以保持相同的顺序,但需要使用
replace
:每次将
=
与字符串一起使用时,它都会创建一个新字符串并将其分配给变量。要替换它而不创建新字符串,请使用String.replace
方法。为了好玩,您可以使用 irb 来测试一下:
You can keep the same order you have, but you need to use
replace
:Every time you use
=
with a string, it creates a new string and assigns it to the variable. To replace it without creating a new string, you use theString.replace
method.For fun, you can use
irb
to test this out:我建议创建一个简单的类:
然后像这样使用它:
通过这种方法,每个数组的第二个元素是一个具有自己的实例变量“netinput”的对象。希望这对你有用。
I recommend making a simple class:
Then use it like this:
With this approach the second element of each array is an object that has its own instance variable "netinput." Hopefully this works for you.