Question about Vector class

Hi,
I am extremely new to Ruby, just my first week so I apologize if this
has
already been discussed or is completely absurd.

I was using the library Vector class defined in matrix.rb in one of my
programs, the [] method in the library class does not check for range
out of
bounds and the []= does not even exist. In my program I extended the
Vector
class as follows -


require ‘matrix’

Extend the Vector library class for []=

defined in src/ruby-1.8.4/matrix.rb

class Vector
include ExceptionForMatrix

[]= not defined in the library class

def []= (i, val)
Vector.Raise ErrDimensionMismatch if i >= @elements.size
@elements[i] = val
end

Fix the [] in library Vector class

def
Vector.Raise ErrDimensionMismatch if i >= @elements.size
@elements[i]
end
end
#-------------------------------------------------------------------------------

Should this not be part of matrix.rb itself?

Best Regards
Nasir

Nasir K. wrote:

I was using the library Vector class defined in matrix.rb in one of my
programs, the [] method in the library class does not check for range out of
bounds and the []= does not even exist. In my program I extended the Vector
class as follows -

class Vector
include ExceptionForMatrix

Once a module has been included, you don’t need to re-include it when
you re-open the class.

[]= not defined in the library class

def []= (i, val)
Vector.Raise ErrDimensionMismatch if i >= @elements.size
@elements[i] = val
end

I haven’t a great deal of experience with matrix.rb, but from the
quick look I just did, it seems that Vector instances are immutable
(un-changeable), like the Numeric classes. Immutability means you can
pass a vector or number into a method and know it won’t be
unexpectedly altered. It means you can think of a vector as a fixed
value, rather than a container.

So your proposed []= method is a bad idea. If you want to be able to
tweak a vector one element at a time, consider using Array (especially
if you’re not wanting a mathematical vector) or a method like the
following, to keep Vector immutable:

def with_element_replaced (i, val)
Vector.Raise ErrDimensionMismatch if i >= @elements.size
new_vec = self.to_a
new_vec[i] = val
Vector[*new_vec]
end

Fix the [] in library Vector class

def
Vector.Raise ErrDimensionMismatch if i >= @elements.size
@elements[i]
end
end

I don’t see a strong argument for this over the existing behaviour.
What you’ve done isn’t wrong, though, and if you find it handy, use
it. You’ve gained early and descriptive failure, but lost a bit of
flexibility in using negative indexes (vec[-1] for the last element).

Cheers,
Dave

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs