Getting single char from string -- Simpler solution?

S

sa 125

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!
 
S

Stefano Crocco

Alle Tuesday 25 November 2008, sa 125 ha scritto:
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!

"hello"[0,1]

"hello"[0..0]

"hello"[0].chr

I hope this helps

Stefano
 
D

Diogo Lisboa

Alle Tuesday 25 November 2008, sa 125 ha scritto:
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!

"hello"[0,1]

"hello"[0..0]

"hello"[0].chr

I hope this helps

Stefano

Just complementing, this is now the default behavior in 1.9:
=> "h" # note no need for .chr

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


Diogo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,189
Messages
2,571,016
Members
47,618
Latest member
Leemorton01

Latest Threads

Top