Please help with code

Hello all.

Somebody please explain the code below

I totally fail to understand how is it possible that my variable var which is in charge of changing the first character from lower to upper case - how can it make the change inside a different variable words. The lower to upper change is being executed for the variable var but I am returning in the end variable words. How does variable words gets it’s characters changed?

I just don’t get it.

Thanks


def capitalize_words(string)
  words = string.split(" ")

  idx = 0
  while idx < words.length
    var = words[idx]
    var[0] = var[0].upcase
    idx += 1
  end 
  

  return words.join(" ")
end
1 Like

Very good question! :thumbsup:

An Array is a collection of objects in Ruby. When you assign a variable to an object in an Array you are not copying or removing it from the Array you’re pointing at the same object. For example look at the ids of the objects in an array.

words = ["apple", "orange", "pizza"]
# => ["apple", "orange", "pizza"]

puts words.map(&:__id__)
# 46992010731060
# 46992010731020
# 46992010730980

var = words[0]
# => "apple"

var.__id__
# => 46992010731060
words[0].__id__
# => 46992010731060


var.__id__ == words[0].__id__
# => true

As you can see in the example above the object id is the same for var as it is for words[0] . So whatever you do on var you’re doing to the object inside the Array of words.

If you want to copy the object and not point to it then you need to use dup.

var = words[0].dup
# => "apple"
var.__id__
# => 46992012076080
words[0].__id__
# => 46992010731060
var.__id__ == words[0].__id__
# => false
1 Like

Wow never knew that. Thanks a lot Daniel. You saved me some headaches for today.
Do you have any idea if javascript works the same way?

Thanks

With JavaScript it’s really hard to tell. But I would say no. It doesn’t behave like Ruby with it. In my experiments JavaScript seems to make a copy and the variable assignment doesn’t make changes in the array when you change the variable object.

JavaScript does a lot of things it shouldn’t. See the video from this post: Wat

That’s what I thought also. Thanks.