From: "Michael W. Ryder" <_mwryder@...> Date: 2007-04-24T02:40:09+09:00 Subject: Re: Question regarding design of the String Class Rick DeNatale wrote: > On 4/22/07, Daniel Martin wrote: >> "Michael W. Ryder" <_mwryder@worldnet.att.net> writes: >> >> > Was there a reason the string class was implemented with str[i] >> > returning the code of position i in str? The reason I ask this is >> > that in other languages str[i] returns the string starting at position >> > i. For example C uses t = strcpy(str[i]) and Business Basic uses >> > S$=T$(I) to copy a string from position i. >> >> I can't comment on what "Business Basic" uses, but your C code is >> completely wrong. In C, str[i] returns a char which, since C has >> "char" as one of its integral types, is equivalent to returning the >> character code. > > Daniel, your points are well taken, but if the rusty old neurons in > my brain which contain knowledge of C aren't mistaken, str[i] isn't a > function, and therefore doesn't 'return' anything. > > C doesn't really have a string type. A string literal is really an > array of chars, although in almost all cases (i.e. either than when > it's used in a string initializer, or as the argument to sizeof), it's > interpreted as a pointer to the first character, due to the > relationship between arrays and pointers in C. > > So if str is declared either as: > > char str[]; > or > char *str; > > the expression str[i] is equivalent to *((str) + (i)), it's really a > pointer to a char, which because of the relationship between arrays > and pointers in c, can be interpreted as an array of chars. > > And in Ruby the whole notion of pointers is meaningless. > > The point here, of course, is that when learning Ruby, or any other > language, one needs to be aware that things one knows from other > languages often don't carry over without conceptual modification, if > at all. > > If all languages did everything exactly the same way, there'd be no > need for so many of them. > > To sum it up, let Ruby be Ruby, don't expect it to be Java, C++, > Visual Basic, or anything else. > I guess my point was that str[i] behaves totally different from all the other implementations of []. All of the others return a string. This seems to be an inconsistency. If there is a valid reason for it I have no problem, it just makes it harder to transfer over 25 years of experience to a new language. In Business Basic or C if I want the numeric value of a character in a string I specify that. Likewise if I want to copy a string from an arbitrary position I don't have to specify an ending character like Ruby. I just find s = t[i, -1] to be much harder to understand in a quick read then s = t[i]. Others may not have this problem.