I want to convert the elements of the string array below to symbols, and output them
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
look at what I'm doing:
strings.each { |x| puts x.to_sym }
No success. What am I doing wrong?
You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Use map
rather than each
:
>> strings.map { |x| x.to_sym } => [:HTML, :CSS, :JavaScript, :Python, :Ruby]
For Ruby 1.8.7 and later or with ActiveSupport included, you can use this syntax:
>> strings.map &:to_sym => [:HTML, :CSS, :JavaScript, :Python, :Ruby]
The reason your each
method appears to not work is that calling puts
with a symbol outputs the string representation of the symbol (that is, without the :
). Additionally, you're just looping through and outputting things; you're not actually constructing a new array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With