This forum is now read-only. Please use our new forums at discuss.codecademy.com.
Intern and to_sym?
- Why have multiple ways to do the same things?
- Is one more efficient with memory?
- Why not just use the one that is more efficient, can they each do something different?
They are just two names for the same method. They do exactly the same thing, there is no difference at all except for the name.
Why have two ways of doing the same thing? Well, that's a silly question. To be able to write expressive code. A language that only has one way to get from A to B is not a language at all. Even in arithmetics, you have countless ways of expressing the same idea, say, of multiplying 5 by 2: you can say
(1+1)*5, so there is always more than one way.
A better question would be why Ruby has two names for the same method. This is just to give the programmer the freedom to write human-readable code that makes the intention of what you're trying to do transparent:
.to_symtells you that a string is being converted to a symbol
.intern, while performing precisely the same task, stresses the fact that it gets you the "internal representation" of the string – because Ruby converts all the string literals that you use in the code to symbols internally.
These synonyms (or aliases) are all over Ruby:
Array#map is the same as
String#succ (successor) is the same as
Hash#each is the same as
Numeric#abs is the same as
You can like it or hate it. Personally I like the expressivity about this – the fact that I can stress what I'm doing (for instance, I might be collecting, not "mapping", even if it makes no difference whatsoever to Ruby).
Another advantage is that if you forget one of the names you might still remember the other, so you don't have to look up, you just use the one synonym your mind was more familiar with. Also, keeping several method names around makes it easier for a programmer to learn Ruby, because in all likelihood one of those names is very similar to what they already know from another programming language.
In my opinion Ruby should not be the first programming language one learns (because it can confuse beginners), but for people that have coded in a couple of other languages before, Ruby is a bliss.
symbols = Array.new
strings.each do |x|
Add your code below!
symbols =  strings.each do |x| symbols.push(x.intern ) end
@Alex J, very nice and easy to understand explanation. Off topic, what then would be best first time programming language?
:one => 1,
:two => 2, # Fill in these two blanks!
:three => 3,
Add your code below!
strings.each do |s|
"For each s in strings, use .to_sym to convert s to a symbol and use .push to add that new symbol to symbols." can we word this like normal humans first then work on wording it like a crazy monkey on a typewriter? for hints can we actually give relevant hints?