DEV Community

Ali Ilman
Ali Ilman

Posted on • Originally published at ali-ilman.com

The String#chars method

Originally published on https://ali-ilman.com/blog/the-string-chars-method.

I was browsing the web and I noticed Ruby code that utilises a String instance method called chars.
Until today, I'd never used nor heard of String#chars. What does it do?

String#chars is used to return an array of characters within a string.

name = 'Ali'
name.chars
=> ["A", "l", "i"]
Enter fullscreen mode Exit fullscreen mode

Do note that it does not work similarly to String#split, although we can achieve the same result.

name = "Ali"
name.split('')
=> ["A", "l", "i"]
Enter fullscreen mode Exit fullscreen mode

So how are String#chars and String#split different to each other?

String#split uses a regular expression to divide characters within a string, thus returning an array.

String#chars parses the byte of each character within a string and then it returns an array.

Cheers for reading! 🤓

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay