Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a array of strings to an array of symbols?

Tags:

ruby

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?

like image 521
Gracko Avatar asked May 11 '13 23:05

Gracko


People also ask

How do I convert a string to an array of numbers?

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.

How do I convert a string to an array in Javascript?

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.


1 Answers

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.

like image 159
icktoofay Avatar answered Sep 28 '22 18:09

icktoofay