Really not understanding this Strings vs. Symbols business


#1

Got to exercise 9 and realized I don't understand what I'm doing here. I got the code right, because I had to look it up, but I still can't grasp why any of this would be necessary or how some of this code works.

symbols = []
strings.each { |s| symbols.push (s.to_sym) }

symbols

Why is [] necessary for anything? .push adds an element to the end of an array but what do they mean by element?

Any clarification would be appreciated. I'm not used to this kind of teaching (outside of a classroom, etc.)


#2

symbols = [] is used to specify that symbols is an array (and also to initialize it with something).

If we don't do that, symbols will not respond to the .push method (because it won't be an array).

An element in an array can be anything: a string like "hello", or an integer like 5, it can even be an array. In our example, we want our array symbols to store (as its name suggests) the symbol versions of our strings array.


#3

Thanks! I understand most of it thanks to you, however I'm not sure what .push is doing here. It adds an element to the end of the array, but I'm not sure how that actually manifests since the console is just displaying the array of strings as symbols. What element am I adding in this situation?


#4

It displays the array of symbols probably because your last instruction in your code returns the array of symbols. it's not part of the output, it's just how the Ruby console in codeacademy works. It just shows that your push into the array symbols was successful.


#5

Okay! Thanks for all your help.