#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]}"
Run Code Online (Sandbox Code Playgroud)
我input_from_the_net稍后在循环中使用变量并将其值分配给散列.然后将该哈希存储在另一个哈希中.如果我使用input_from_the_net.replace("a value scraped from the net")它替换所有哈希值中的值.这是不希望的.我希望所有哈希都保持正确的值.
`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
Run Code Online (Sandbox Code Playgroud)
Q1:我可以做这项工作而不是改变线的顺序吗?
Q2:如果我#input_from_the_net = ""在打印时取消注释变量input_from_the_net的值是""而不是"从网上刮下的值".怎么会?
您可以保持相同的订单,但需要使用replace:
input_from_the_net = ""
my_array = [ ["Header name" , input_from_the_net] ]
input_from_the_net.replace("a value scraped from the net")
puts "#{my_array[0][0]} is #{my_array[0][1]}"
# Outputs: Header name is a value scraped from the net
Run Code Online (Sandbox Code Playgroud)
每次使用=字符串时,它都会创建一个新字符串并将其分配给变量.要在不创建新字符串的情况下替换它,请使用该String.replace方法.
为了好玩,您可以irb用来测试它:
>> str = "Hello"
=> "Hello"
>> str.object_id
=> 2156902220 # original id
>> str = "New String"
=> "New String"
>> str.object_id
=> 2156889960 # different id
>> str.replace("Third String")
=> "Third String"
>> str.object_id
=> 2156889960 # same id
Run Code Online (Sandbox Code Playgroud)