Alternate Solution to Converting Between Symbols and Strings?


#1




Hi, I've found the correct solution to this lesson, but I hope to understand why the approach below, which was my first thought, doesn't work. I saw from past posts regarding this same approach that "we cannot convert in place" or that "You need to re-assign the result of s.to_sym back to s.".

So is the problem that the result of "s.to_sym" below is not actually altering s so that it can be fed into the next line, since s is a flexible placeholder that is used to represent each different member of the array? (In my original thinking, I think I'd assumed that Ruby would cycle through the whole process for each string in the array, and that the s would -- within the span of one cycle -- maintain any alterations it underwent and build on them in sequence until the process reached a conclusion, at which point it would start over for the next member of the array and bring it through the same alterations. It seems this was incorrect. )

If we were to take an approach where after using s.to_sym, we then wanted to re-assign the result of s.to_sym back to s, what would that look like?


strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols=[]
strings.each do |s|
    s.to_sym
symbols.push(s)
end


#2

You'd just assign s to the symbol, there's nothing else to it. s would then refer to the symbol instead of the string


#3

Ok, thank you. I tried the below solution after reading your comment and see that it would also work. I guess my mistake was thinking that typing s.to_sym was fundamentally altering the s variable, whereas I guess in my first approach above, that 's.to_sym' line was actually just not doing much of anything correct? I mean in context it had no effect on anything? Like where would that new symbol that was created from s have been stored or registered, or it just wouldn't have?


#4

The symbol is created but you don't assign a variable to it so it gets discarded
Changing the type of a value while still being the same value would be very confusing, imagine having a string that suddenly stops being a string, how would you now know how to interact with it? If you can overwrite the current value then you can just as well write somewhere else instead and refer to that. If nobody else has a reference to the old value then it'll get removed from memory by the garbage collector


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.