From: Eleanor McHugh Date: 2009-05-09T09:37:54+09:00 Subject: Re: ruby string slice/[] w/ range, weird end behavior On 9 May 2009, at 01:19, Gary Yngve wrote: > On May 8, 4:47 pm, Eleanor McHugh > wrote: >> "foo"[3..3] => "" > ... >> index [3] is actually the end of the string so whilst the range >> accesses the string after any characters in it, it's still accessing >> the string in a valid range. > > Maybe in the native C. But why should that be exposed? It's not the C implementation, it's the conceptual model of what a string is: i.e. an array of characters addressable by index and range. > And why shouldn't index[3] return "" if you are correct? Because in this case the question you're asking isn't "What substring occupies the given segment of the string" but "Which character is stored at the given index in the string". If no character is stored there (as the case for "foo"[3]) then nil is the only meaningful answer. "foo"[3] => nil nil.to_s => "" > After all: > >>> a=[]; "asd".each_byte{|x| a << x}; a > => [97, 115, 100] > > If I ask for a substring entirely out of bounds, I should consistently > be returned nil or "", not one of the two. And the substring "foo"[3..3] is in bounds because conceptually you're dealing with: f o o 0 1 2 3 so [3..3] equals the slice at the end of the string but not containing any characters. And yes, I know this is probably about as clear as mud - my ability to write English seems to be inversely proportional to the difficulty of the code I'm working on at any given time, and currently I'm buried in research so the code is very hairy indeed :( Whilst it's not directly relevant, being a different language and all, I recommend "Chapter 3: String Processing" in Programming with Unicon (http://unicon.sourceforge.net/ubooks.html ) as it's the same basic model. Ellie Eleanor McHugh Games With Brains http://slides.games-with-brains.net ---- raise ArgumentError unless @reality.responds_to? :reason