2
\$\begingroup\$

How can I make these methods better?

Range.class_eval do
    def addto_begin(x)
        return self.begin + x..self.end
    end
    def addto_end(x)
        return self.begin..self.end+x
    end
end

Right now, I have to type:

x = 1..10
x = x.addto_begin(3)

to change the begin of the range. What I want to be able to do is:

x = 1..10
x.addto_begin(3)

How do I do this?

\$\endgroup\$
0

2 Answers 2

3
\$\begingroup\$

Since ranges are immutable you would need to create your own range class that encapsulates the basic range object. This class will give you that and still keep and the methods associated with the basic range object.

class Myrange
  attr_accessor :range
  def initialize(a,b=nil,exc=false)
    if a.is_a? Range
      @range = a
    else
      @range = Range.new(a,b,exc)
    end
  end
  def addto_begin(x)
    Myrange.new(@range.begin + [email protected])
  end
  def addto_end(x)
    Myrange.new(@[email protected]+x)
  end
  def addto_begin!(x)
    @range = @range.begin + [email protected]
    Myrange.new(@range)
  end
  def addto_end!(x)
    @range = @[email protected]+x
    Myrange.new(@range)
  end
  def to_s
    @range.to_s
  end
  def inspect
    self.to_s
  end
  def method_missing(*args,&blk)
    @range.send(*args,&blk)
  end
end

x = Myrange.new(1,10)
x = x.addto_begin(3)
p x #=> 4..10
y = x.addto_begin!(3)
p x #=> 7..10
p y.addto_end(3) #=> 7..13
p x.include? 9 #=> true :: Range methods still work
\$\endgroup\$
1
\$\begingroup\$

You can't. Range doesn't provide write access to properties (i.e. begin/end).

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.