Walter Straub Walter Straub -4 years ago 115
Ruby Question

Converting strings to symbols and ".push"ing them into an array

This is from a Codecademy lesson and I am aware people have asked about it on here, but I want to see what is wrong with my solution in particular. Here is what they start you out with:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

# Add your code below!


Here are the instructions:


We have an array of strings we'd like to later use as hash keys, but we'd rather they be symbols.

Create a new variable, symbols, and store an empty array in it. Use
.each to iterate over the strings array. For each s in strings, use
.to_sym to convert s to a symbol and use .push to add that new symbol
to symbols.


I apologize as the formatting did not copy over prefectly, but you get the idea.

Here is my solution:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

# Add your code below!

symbols = []
strings.each do |s|
s.to_sym
symbols.push(s)
end


Upon submitting this, I get the error that I did not correctly convert the string to a symbol.

Answer Source

You create a new symbol from the string that s points to, but you don't change s (it's still a string) and you don't use the new symbol. Instead, your loop should contain the code

symbols.push(s.to_sym)

Note that the question requires you to use .each, so the answer suggesting .map is wrong, even though it's a better way of implementing the same thing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download