Forum: Ruby Getting single char from string -- Simpler solution?

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.
7db3b1680807d393d40260591b4ae5e0?d=identicon&s=25 sa 125 (sa125)
on 2008-11-25 13:51
Hi -

I'm trying to get a single char from string, but doing it like this
return the ascii key:

irb(main):060:0> "hello"[0]
=> 104

I know this could be accomplished like this:

irb(main):063:0> "hello".split('')[0]
=> "h"

I'm not too lazy to type, but I was wondering if there's a simpler way I
overlooked.

Thanks!
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2008-11-25 13:54
(Received via mailing list)
Alle Tuesday 25 November 2008, sa 125 ha scritto:
> irb(main):063:0> "hello".split('')[0]
> => "h"
>
> I'm not too lazy to type, but I was wondering if there's a simpler way I
> overlooked.
>
> Thanks!

"hello"[0,1]

"hello"[0..0]

"hello"[0].chr

I hope this helps

Stefano
5ff576dcf253c4469b51e7245c22808a?d=identicon&s=25 Diogo Lisboa (Guest)
on 2008-11-25 14:19
(Received via mailing list)
On Tue, Nov 25, 2008 at 10:49 AM, Stefano Crocco
<stefano.crocco@alice.it> wrote:
>>
> "hello"[0..0]
>
> "hello"[0].chr
>
> I hope this helps
>
> Stefano
>

Just complementing, this is now the default behavior in 1.9:

>> "hello"[0]
=> "h"  # note no need for .chr

For 1.8, "hello"[0,1] sounds sounds like what you'd want in those
situations.


Diogo
7db3b1680807d393d40260591b4ae5e0?d=identicon&s=25 sa 125 (sa125)
on 2008-11-25 14:48
Thanks guys, that's exactly what I was looking for.
This topic is locked and can not be replied to.