Frage

I'm trying to put an array to another existing array and moreover to put all its items to an existing set. Here's the minimal example:

require "set"

def add(myarr, bigarr, myset)
    bigarr << myarr
    myset |= Set.new(myarr)
end

bigarr = []
myset = Set.new

add([1, 2], bigarr, myset)

Which yields bigarr = [1, 2] .. OK, but myset = {} .. is empty. I know little about passing arguments in Ruby (should be by-value) -- in case of array the value should be a reference to its content, then I have no clue what could be the value of set.

The questions are:

  1. What is the substantial difference between Array and Set which causes this behavior?
  2. Is there any way to force Ruby pass-by-reference or is there a different recommended way how to solve the problem with referencing?

Thanks in advance!

War es hilfreich?

Lösung

This doesn't have anything to do with the difference between arrays and sets. You're modifying the array with the << method, but you're reassigning the myset variable with the |= operator. You never modify the set you passed in. What you want is probably myset.merge(myarr).

Andere Tipps

The problem here actually comes from this particular line:

 myset |= Set.new(myarr)

Here you're creating new object on old variable name. You're replacing one pointer with another, however this only modifies local copy of it. Original object will still exists in memory and outside function, pointer will point to old object (empty set) (tbh: I would not really encourage this kind of writing in ruby with side effects).

If you change it to

require "set"

def add(myarr, bigarr, myset)
    bigarr << myarr
    myset.add(myarr)
end

bigarr = []
myset = Set.new

add([1, 2], bigarr, myset)

It's working properly - because you modify existing object and don't create new one.

There is great answer that goes more thoroughly into this, right here: https://stackoverflow.com/a/16464640/1975116

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top