syzygy333 syzygy333 - 11 months ago 59
Ruby Question

Codecademy "converting between symbols and strings" ruby lesson

These are Codecademy's 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 array, symbols. Use
to iterate over the strings array and convert each string to a symbol, adding those symbols to symbols.

This is the code I wrote (the
array was provided):

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = []
strings.each { |x| x.to_sym }

I know I'm probably doing multiple things wrong, but I've got through the ruby track this far with very little difficulty, so I'm not sure why this one is stumping me. Firstly, it's not converting the strings to symbols, and secondly, it's not pushing them to the symbols array.


The to_sym alone wasn't doing anything useful; it was converting the string, but not storing it anywhere or using it later. You want to keep adding to symbols array.

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = []
strings.each { |s| symbols.push s.to_sym }

Or more elegantly, you can skip setting symbols = [] and just use map to create it in one line:

symbols = { |s| s.to_sym }

map will walk through each item in the array and transform it into something else according to the map function. And for simple maps where you're just applying a function, you can take it a step further:

symbols = &:to_sym

(That's the same as symbols =, use whichever you find more tasteful.)