How to convert an array of strings into values (symbols)?

Viewed 48

How can I easily convert

a = [ "b", "c", "d" ]

into

a = [ :b, :c, :d ]

and vice versa?

I went through the docs but didn't find a solution

2 Answers

you can call to_sym on each element in a map:

a.map { |letter| letter.to_sym }
=> [:b, :c, :d]

To iterate over an array, returning a new array with updated values, use Array#map. That's the key method you need to know about.

I'm not sure what you mean by "converting strings into values", but objects like :b in ruby are called Symbols.

You can convert a String into a Symbol by calling to_sym. (And vice-versa by calling to_s.)

So putting this all together, you can convert the array by doing this:

a = [ "b", "c", "d" ]
a.map { |letter| letter.to_sym }
  # => [:b, :c, :d]

# Or equivalently, there's a shorthand for this:
a.map(&:to_sym)

If you want to update the original array, rather than return a new array, use Array.map! instead of Array.map:

Related