Converting Between Symbols and Strings


#1

how i can know if the string have an 's' to convert it to a symbol?

for a weird reason i can pass to next lesson with the code below:
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

# Add your code below!
symbols = []

strings.each do |key|
    symbols.push(key.to_sym)
end

#2

Which exercise is that?


#3

I am on that exercise now. They are requesting:

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 used the below code and was told it was correct. However the objects still appear as strings rather than symbols when printed to the console.

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

symbols = []

strings.each do |string|
symbols.push(string.to_sym)
end


#4

@webrunner12662

Yes, because each returns the content of the strings array (because it was called on it), and not the symbols array.

If you want to check you can simply add the instruction:

symbols

at the end of your code and you'll see that the array will be returned as an array of symbols.


#5

Thanks for the feedback. Yet, the section of the question which asks to convert each s in strings is still unanswered. Help please.


#6

You probably mean each string containing an 's', in which case the include? method does the job.


#7

what would the syntax look like then?


#8

The syntax for the include? method was presented in previous lessons, for example this one:

https://www.codecademy.com/courses/ruby-beginner-en-JdNDe/0/1?curriculum_id=5059f8619189a5000201fbcb


#9

Great! Thanks. I knew it was somewhere in the course. I just couldn't find it.


#10

Is the "s" mentioned in the question meaning "string" actually? not the "s" letter of each string?


#11

Yea this was a little tricky for me to. They aren't referring to the letter "s" but telling you to assign "s" as the variable for each string. This code works

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

Add your code below!

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


#12

Why doesn't this code work?

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


#13

This will only convert s to a symbol but nothing else. It will not modify s.

You can use:

s = s.to_sym

Or better yet, you can simply use to_sym inside your push method.


#14

Yes. "s" means the string in the array.