开发者

can I declare an array where one of the array elements is undeclared variable? (ruby)

#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 th开发者_StackOverflowe net". How come?


You can keep the same order you have, but you need to use 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

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 the String.replace method.

For fun, you can use irb to test this out:

>> 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


I recommend making a simple class:

class Netinput
  attr_accessor :netinput

def initialize(netinput = "")
  @netinput = netinput
end

end

Then use it like this:

input_from_the_net = "our test string"

#Netinput can take a string or no argument
my_array = [ ["Header name" , Netinput.new()] ]

my_array[0][1].netinput = input_from_the_net

puts "#{my_array[0][0]} is #{my_array[0][1].netinput}"

# Outputs: Header name is our test string

With this approach the second element of each array is an object that has its own instance variable "netinput." Hopefully this works for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜