[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: accessing each character of a string

Peña, Botp

5/19/2005 2:03:00 AM


# a = "hello there"
# a[1] #=> 101
# a[1,3] #=> "ell"
# a[1..3] #=> "ell"
# a[-3,2] #=> "er"
# a[-4..-2] #=> "her"
# a[12..-1] #=> nil
# a[-2..-4] #=> ""
# a[/[aeiou](.)\1/] #=> "ell"
# a[/[aeiou](.)\1/, 0] #=> "ell"
# a[/[aeiou](.)\1/, 1] #=> "l"
# a[/[aeiou](.)\1/, 2] #=> nil
# a["lo"] #=> "lo"
# a["bye"] #=> nil
#


From this, i think a[1] is the odd one out.
I'd prefer a[1] #=> "e"


4 Answers

Assaph Mehr

5/19/2005 2:26:00 AM

0


Peña, Botp wrote:
> From this, i think a[1] is the odd one out.
> I'd prefer a[1] #=> "e"

I tend to agree, but I long since came to believe that Matz knows
better than me :-)
I'm sure there's a good reason why it's made this way even if it's not
immediately obvious.

Hal E. Fulton

5/19/2005 3:31:00 AM

0

Assaph Mehr wrote:
> Peña, Botp wrote:
>
>>From this, i think a[1] is the odd one out.
>>I'd prefer a[1] #=> "e"
>
>
> I tend to agree, but I long since came to believe that Matz knows
> better than me :-)
> I'm sure there's a good reason why it's made this way even if it's not
> immediately obvious.
>

Actually, I believe this is going to change in the
future. Anyhow, Gavin K's workaround (see previous post)
is what I tend to use.


Hal




Xevious

5/19/2005 3:40:00 AM

0

Assaph Mehr wrote:
> Peña, Botp wrote:
>
>>From this, i think a[1] is the odd one out.
>>I'd prefer a[1] #=> "e"
>
> I tend to agree, but I long since came to believe that Matz knows
> better than me :-)
> I'm sure there's a good reason why it's made this way even if it's not
> immediately obvious.

Because a[1] is a single char - not a "string" of chars.

OTOH, the range returns string so a[1..1] returns a string
containing 1 char.

xev





Lawrence Oluyede

5/19/2005 8:25:00 AM

0

Hal Fulton <hal9000@hypermetrics.com> writes:

> Actually, I believe this is going to change in the
> future. Anyhow, Gavin K's workaround (see previous post)
> is what I tend to use.

Yeah I think it's the better workaround, using range to extract
a single char seems very odd to me. Anyway I prefer the Python
"style" where "hello"[0] returns the char and you can always
use ord() function to get the number. How many people iterate
trough strings to get the ordinal numbers? In my own opinion
the default behavior should be iterating over chars (or strings
of length 1) not over ordinal numbers... but as stated in another
post... Matz should have a reason to do in this way.

--
Lawrence
http://www.oluyed...