简体   繁体   中英

Why is Ruby method argument value inexplicably changed?

Here is some code for a method that is supposed to eventually compare a scrambled word to a small "dictionary" of words and return the word, unscrambled. Keep in mind that this method is incomplete.

def word_unscrambler(str, words)
  p words
  comparison = words.each_index {|i| words[i] = words[i].chars.sort.join}
  p words
  string = str.chars.join
  comparison.each_index do |i|
    return words[i] if string == comparison[i]
  end
end

When I test the method using irb and a list of fruit for the argument "words", the first "p words" outputs:

["apple", "orange", "pineapple"]

The second "p words" outputs:

["aelpp", "aegnor", "aeeilnppp"]

I am confused that the values of the array "words" is changed after the assignment statement of "comparison". Yes, "comparison" is assigned to a modification of "words", but in my experience an assignment statement only assigns a value to the variable on the left of the assignment operator. Even though this goes against everything I've learned in my time programming, I tried to isolate "words" by making another array with the same values, called "copy". With this modification to my code, I still ended up getting "words" with reassigned values. I must be missing some fundamental aspect of method arguments or variables.

So, what accounts for the change?

Look a little closer at your comparison = line:

comparison = words.each_index {|i| words[i] = words[i].chars.sort.join}

Inside your each_index block, you are changing the value of each string in your array:

words[i] = words[i].chars.sort.join

This is modifying each string in words. So you would expect "apple" to become "aelpp"

To build a new array and assign it to comparison, you might want to take a look at the map method .

comparison = words.map { |word| word.chars.sort.join }

This would create and assign a new array to comparison that would look like the output from your second p statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM