Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 361
RubenLaguna Avatar asked Jan 10 '23 12:01

RubenLaguna


1 Answers

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.

like image 60
RubenLaguna Avatar answered Jan 19 '23 05:01

RubenLaguna