Forum: Ruby How to convert a String to an Array?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D3e9a0c5baec3681545c567bef36825b?d=identicon&s=25 RubyCrazy (Guest)
on 2007-03-16 13:18
(Received via mailing list)
Is there a way to convert a String to an Array? I could only find the
following -
'hello world'.scan(/./)

Thanks.
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2007-03-16 13:25
(Received via mailing list)
On 16/03/07, RubyCrazy <rubycrazy@gmail.com> wrote:
> Is there a way to convert a String to an Array? I could only find the
> following -
> 'hello world'.scan(/./)
>
> Thanks.
>

irb(main):001:0> "hello world".split(//)
=> ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

I'm not sure if this is functionally the same or if there is some kind
of performance boost using split instead of scan.

Farrel
F50f5d582d76f98686da34917531fe56?d=identicon&s=25 Peter Szinek (Guest)
on 2007-03-16 13:31
(Received via mailing list)
RubyCrazy wrote:
> Is there a way to convert a String to an Array? I could only find the
> following -
> 'hello world'.scan(/./)

And what's the problem with that? Or do you want a different result?

Alternatively you can do

'hello world'.split(' ')

or

'hello world'.split(/\s+/)

if you want to split on any number of whitespace chars.

If you want to split just on single spaces, your original solution is
faster.


Cheers,
Peter
__
http://www.rubyrailways.com :: Ruby and Web2.0 blog
http://scrubyt.org :: Ruby web scraping framework
http://rubykitchensink.ca/ :: The indexed archive of all things Ruby
This topic is locked and can not be replied to.