[Note: parts of this message were removed to make it a legal post.]
On Tue, Jul 13, 2010 at 4:26 PM, Abder-Rahman Ali <
I'm not really sure what you're asking, but I think that it is probably
answered by the docs:
http://ruby-doc.org/core/classes/String.html#M000771
str[range] => new str or nil
<
http://ruby-doc.org/core/classes/String.src/M000771.html>If given a
range,
a substring containing characters at offsets given by the range is
returned.
In all three cases, if an offset is negative, it is counted from the end
of
*str*.
Thanks Josh.
For example, this from the documentation:
a = "hello there"
a[-3,2] #=> "er"
-3 ---> Start counting from 0 to 3 from the end (Right -> Left)
In this case I reached the letter "h" of there
2 ---> What should I do here?
Thanks.
[/QUOTE]
The first character is zero, the last character is negative one (there is no
negative zero), when you count backwards from the end:
-1: e
-2: r
-3: e
-4: h
-5: t
So, as the docs say "If passed two
Fixnum<
http://ruby-doc.org/core/classes/Fixnum.html>objects, returns a
substring starting at the offset given by the first, and
a length <
http://ruby-doc.org/core/classes/String.html#M000774> given by the
second."
-3,2 puts you at the e in -3, and returns two characters forward from that
spot. If you are having a difficult time seeing what you could expect, try
giving different numbers in irb, as James suggested.
Open IRB, say "if this thing the docs are telling me is correct, and I
correctly understand it, then I expect xxx to happen when I yyy" Then yyy,
and see if you get xxx. If you do, that means you probably understand it
right. If not, you probably need to experiment more to get a better idea of
what is happening. You can try following patterns to see how the results
change with the pattern:
a[-4,2]
a[-5,2]
a[-6,2]
a[-6,3]
a[-6,4]
Find the patterns in the output, make a hypothesis, see if it gives you what
you expected.