#9 to_sym


#1

Hello, everyone. I was just wondering why my code doesn't work.

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

I know the answer to this problem is:

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

but I can't figure out why. Why is the to_sym method applied to the s variable while it's simultaneously being passed as an argument to the .push method? It seems like you would want to convert s to symbols and then simply pass s as the argument, parameter, or whatever. Just needing a little clarification. Thank you.


#2

This is not an in-place method, so needs to be assigned to a variable, or...

symbols.push()

passed as a argument to a method.


#3

Got it. Thank you for the response.


#4

maybe this could be mentioned somewhere in this section, because code academy gives an example of how to convert to a symbol using an in place method, but does not mention requiring the conversion to be done within the argument to the .each method, which is what is expected to pass this section. i don't believe this is intuitive and clarification for new programmers would be beneficial in this case.


#5

There is no in place method. We must cache the new representation in order for it to have an effect.

my_symbol = string.to_sym

string in the above does not get transformed, only the representation does.

string.capitalize!

This is an example of an in place transformation.

 >  string = "dog"
=> "dog"
 > string.to_sym!
(eval): undefined method `to_sym!` for "dog":String (NoMethodError)

 > string.to_sym
=> :dog
 > string
=> "dog"

Notice that the expression creates the symbol, but it is not cached. This is why we can pass it as an argument. An argument may be any expression that yields a value.


#8