SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
Thread: Question regarding ranges
-
Nov 18, 2007, 19:35 #1
- Join Date
- Sep 2005
- Location
- Toronto, Canada
- Posts
- 195
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Question regarding ranges
I'm in the process of trying to understand how to generate ranges, and I'm having trouble understanding what each method does within the following class (Source):
Code Ruby:class Xs # represent a string of 'x's include Comparable attr :length def initialize(n) @length = n end def succ Xs.new(@length + 1) end def <=>(other) @length <=> other.length end def to_s sprintf "%2d #{inspect}", @length end def inspect 'x' * @length end end r = Xs.new(3)..Xs.new(6) #=> xxx..xxxxxx r.to_a #=> [xxx, xxxx, xxxxx, xxxxxx] r.member?(Xs.new(5)) #=> true
The two I'm having particular trouble understanding are the succ & inspect methods.
-
Nov 19, 2007, 07:21 #2
I don't know how familiar with Ruby you are, but the first thing to remember is that methods don't need an explicit return statement. They naturally return the value of the last statement executed. That means that:
- succ will return the "next" X in the sequence. It instantiates a new X object with a @length value equal to the current @length plus one. The succ method is the ++ operator of Ruby (with the difference that it returns a new object, instead of incrementing the original)
- inspect will return a string formed by "x", repeated @length times. If you check the documentation for String, you'll see the * (multiplication) method overriden there. The inspect method is used by the debugger (and when you print an object with p, that's the method it calls)
Last edited by ruby-lang; Nov 19, 2007 at 08:23.
-
Nov 20, 2007, 11:41 #3
- Join Date
- Sep 2005
- Location
- Toronto, Canada
- Posts
- 195
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
I guess what I'm having trouble understanding is how succ does its thing without being explicitly called. I understand that initialize is automatically called upon during the formation of a new instance of a class (in this case Xs); is the same true for succ?
-
Nov 20, 2007, 13:20 #4
- Join Date
- Apr 2004
- Location
- germany
- Posts
- 4,324
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
succ is called implicitly by the Range.to_a method
-
Nov 20, 2007, 18:28 #5
- Join Date
- Sep 2005
- Location
- Toronto, Canada
- Posts
- 195
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Great Thanks guys!
Bookmarks