Codecademy "converting between symbols and strings" ruby lesson
Solution 1
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 = strings.map { |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 = strings.map &:to_sym
(That's the same as symbols = strings.map(&:to_sym)
, use whichever you find more tasteful.)
Solution 2
each
iterates over strings
, apply the block to every element. However, it doesn't return anything. You'll want to add to the symbols
array in the block itself:
strings.each { |x| symbols.push(x.to_sym) }
However, you can generate a symbols array in one line as well:
symbols = strings.map { |x| x.to_sym }
Solution 3
You can change your code to the following:
strings.each do |x|
x = x.to_sym
symbols.push(x)
syzygy333
Updated on June 27, 2022Comments
-
syzygy333 almost 2 years
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
.each
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
strings
array was provided):strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"] symbols = [] strings.each { |x| x.to_sym } symbols.push(strings)
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.
-
syzygy333 about 11 yearsthank you. i'm going with your top answer, since i've not yet come across
map
in the lessons. -
mahemoff about 11 yearsThanks - check out the API, there's a lot of neat built-in functions like map. ruby-doc.org/core-2.0/Enumerable.html
-
noobninja almost 8 years2nd example created a symbol array using
irb
, but CA did not. CA only allowed 1st example. another example would bestrings.each { |s| symbols.push s.intern }
-
Admin over 7 yearsMy answer was based on exactly why the the code was not converting the strings to symbol and subsequently not pushing them to symbols arrary based on the codecademy instructions and example given to the learner at that point of the course.
-
Admin over 7 years@Matt kindly, bare in mind, the learner had not been introduced to .map at this point of his/her learning track on Codecademy