From: Josh Cheek Date: 2010-07-14T07:22:23+09:00 Subject: Re: What does this do? --0016e6567fb046e5da048b4c4db8 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jul 13, 2010 at 5:09 PM, Abder-Rahman Ali < abder.rahman.ali@gmail.com> wrote: > Josh Cheek wrote: > > On Tue, Jul 13, 2010 at 4:26 PM, Abder-Rahman Ali < > > abder.rahman.ali@gmail.com> wrote: > > > >> > >> Thanks. > >> -- > >> Posted via http://www.ruby-forum.com/. > >> > >> > > 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 > > > > 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. > > > > -- > Posted via http://www.ruby-forum.com/. > > 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 Fixnumobjects, returns a substring starting at the offset given by the first, and a length 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. --0016e6567fb046e5da048b4c4db8--