RubenLaguna
RubenLaguna

Reputation: 24656

How to convert a string to an array of chars in ruby?

Let's say that you have a string "Hello" and you want an array of chars in return ["H", "e", "l", "l", "o"].

Although it's a simple question I couldn't find a direct answer.

Upvotes: 6

Views: 3277

Answers (1)

RubenLaguna
RubenLaguna

Reputation: 24656

There are several ways to get an array out of a String. #chars which is a shortcut for thestring.each_char.to_a is the most direct in my opinion

>> "Hello".chars
=> ["H", "e", "l", "l", "o"]

The are other ways to get the same result like "Hello".split(//) but they are less intention-revealing.

Upvotes: 11

Related Questions