2

I am trying to do it this way:

$var = 0 #This stay inside a JSON Object
newVar = []

n.times do |i|
  newVar.push(randomize($var))
end

def randomize(thisVar)
  thisVar = Random.new.rand(0 .. 100)
  return thisVar
end

But I always end up with the same value on all vars inside the array newVar[]

I've tried the.dup and .clone to not give the same value to all fields. But it's not working.

Real Code:

    # IdeenAG: Operacoes Geneticas
    def novaPopulacao ()
        puts "\n\nIdeenAG: Criando Populacao ("+$parametros['populacaoInicial']+")\n"

        tempVar = []
        populacaoCriada = []
        xtimes = $parametros['populacaoInicial'].to_i

        xtimes.times do |i|
            populacaoCriada.push(mutar($variaveis.clone))
        end

        puts populacaoCriada.to_s+"\n"
        return populacaoCriada
    end

def mutar (varArray)
    varArray.each_with_index do |variavel,index|
        puts "IdeenAG: Mutando População ("+variavel['nome']+")\n"
        variavel['valor'] = Random.new.rand(variavel['minimo'].to_i .. variavel['maximo'].to_i)
    end

    return varArray
end

Real Result (With 3 Vars)

[[
{"nome"=>"var0", "minimo"=>"1", "maximo"=>"99999", "valor"=>70356}, 
{"nome"=>"var1", "minimo"=>"1", "maximo"=>"99999", "valor"=>55356}, 
{"nome"=>"var2", "minimo"=>"1", "maximo"=>"99999", "valor"=>65904}
], 
[
{"nome"=>"var0", "minimo"=>"1", "maximo"=>"99999", "valor"=>70356},      
{"nome"=>"var1", "minimo"=>"1", "maximo"=>"99999", "valor"=>55356},   
{"nome"=>"var2", "minimo"=>"1", "maximo"=>"99999", "valor"=>65904}
], 
[
{"nome"=>"var0", "minimo"=>"1", "maximo"=>"99999", "valor"=>70356}, 
{"nome"=>"var1", "minimo"=>"1", "maximo"=>"99999", "valor"=>55356}, 
{"nome"=>"var2", "minimo"=>"1", "maximo"=>"99999", "valor"=>65904}
],
[
{"nome"=>"var0", "minimo"=>"1", "maximo"=>"99999", "valor"=>70356}, 
{"nome"=>"var1", "minimo"=>"1", "maximo"=>"99999", "valor"=>55356}, 
{"nome"=>"var2", "minimo"=>"1", "maximo"=>"99999", "valor"=>65904}
],
[
{"nome"=>"var0", "minimo"=>"1", "maximo"=>"99999", "valor"=>70356}, 
{"nome"=>"var1", "minimo"=>"1", "maximo"=>"99999", "valor"=>55356}, 
{"nome"=>"var2", "minimo"=>"1", "maximo"=>"99999", "valor"=>65904}
]]

See the field "valor", it is always the same value! I need to randomize it.

thesecretmaster
  • 1,950
  • 1
  • 27
  • 39
  • It sounds like english may not be your first language. We also have spanish stack overflow: https://es.stackoverflow.com and Portuguese: http://pt.stackoverflow.com/ – thesecretmaster Nov 09 '15 at 21:00
  • The simple example seem to work as intended. Why you had removed the inline code of the orginal? We prefer inline code over screenshots. – Meier Nov 09 '15 at 21:52
  • And what exactly is in $variaveis? I think this global var key to the problem. – Meier Nov 09 '15 at 21:54
  • Please don't post links to your code or use images. We can't reuse images when searching or testing your code, and links rot then break, leaving the question with information missing. Instead, insert the minimal code necessary to demonstrate the problem, along with the necessary input data and your expected output data. Please read "[ask]". In Ruby we use snake_case so use `this_var` and `new_var` instead of `thisVar` and `newVar`. – the Tin Man Nov 09 '15 at 22:36
  • @theTinMan is snake case really a ruby convention? I've seen both camel and snake case used, and don't see why it would make a difference. – thesecretmaster Nov 10 '15 at 00:23
  • @HelcioMacedo Could you post more of your code? How are your methods called and what are `$parametros` and `varivel` set to? – thesecretmaster Nov 10 '15 at 00:27
  • Yes, it's the convention for Ruby. Methods and variables are snake_case and Classes are CamelCase. https://github.com/bbatsov/ruby-style-guide#snake-case-symbols-methods-vars and https://github.com/styleguide/ruby. No_differences_as_far_as_readability? ThereIsABigDifferenceInReadability. – the Tin Man Nov 10 '15 at 00:33
  • i've used the code posted on the "meier" answer.. and it works fine! newVar = Marshal.load( Marshal.dump(oldVar) ) ..... Thanks a lot for all!!! – Helcio R. Macedo Pandelo Nov 10 '15 at 02:39

2 Answers2

1

To correct your first bit of code, are you looking for:

$var = 0 #This stay inside a JSON Object
newVar = []

n.times do |i|
  newVar.push(randomize)
end

def randomize
  thisVar = Random.new.rand(0 .. 100)
  return thisVar
end

This would set newVar to an array of random numbers between 0 and 100. The length of the array would be n.

thesecretmaster
  • 1,950
  • 1
  • 27
  • 39
  • Or you can just call the `rand` method directly as: `newvar.push(rand(0..100))` – x6iae Nov 09 '15 at 20:56
  • in my case.. i have 1 array with x number (this x will be the value of one input field) of JSON objects with 3 parameters on each one.. one of this parameter is the "value" of it.. When i try to randomize it.. it works.. And i put this JSON Object in a new Array with your new value.. And do the iteration again.. and here will the the problematic.. Hes will set the last random value to all another JSON Objects who its stored before this iteration :/ – Helcio R. Macedo Pandelo Nov 09 '15 at 21:10
  • i've posted a printscreen of my code and result on console.. see on the first post.. maybe will be more easyest to understand me :) – Helcio R. Macedo Pandelo Nov 09 '15 at 21:22
1

Both dup and clone only make shallow copys, this means they copy only the top level structure. A typical json is deeply nested.

An example. First without copy:

h1 = {a:"a", b:1}
h2 = h1
h1[:a] = "aa"
h2[:a]

This returns "aa" as expected, because h1 and h2 are the same object.

Now with a dup

h1 = {a:"a", b:"b"}
h2 = h1.dup
h1[:a] = "aa"
h2[:a]
# returns "a", everything looks good
h1[:b].upcase!
h2[:b]
# returns "B" :-(

The h2 hash is new, but in contains pointers to the old objects. If you edit these objects in place, h2 will get also these edits.

So how to get around this? Typically, you just create the jsons objects from scratch. You can also make a deep copy, look for example at this question here:

Ruby dup/clone recursively

Community
  • 1
  • 1
Meier
  • 3,858
  • 1
  • 17
  • 46