1

I need some help with my +/- overridden method, it is not affecting the elements of wektor array.

class Wektor
  attr_accessor :coords

  def initialize(length)
    @coords = Array.new(length, 0)
  end

  def set!(w)
    @coords = w.dup

    self
  end

  %i(* /).each do |op|
    define_method(op) do |n|
      coords.map! { |i| i.send(op, n) }

      self
    end
  end

  %i(- +).each do |op|
    define_method(op) do |v|
      @coords.zip(v).map { |a, b| a.send(op, b) }

      self
    end
  end

  def shift_right!
    coords.rotate!
    coords[0] = 0

    self
  end


end

So basically if a = Wektor.new(4).set!([1,2,3,4] and b = Wektor.new(4).set!([1,1,1,1] I want a-b to set a = [0,1,2,3] What is wrong with this method? It is not changing anything - a is still set to [1,2,3,4].

I tried debugging with IRB but it doesn't give me any clue on what is wrong.

The code looks good to me, but I'm a beginner when it comes to writing ruby-way code (I'm not the author of this piece of code) and I have trouble spotting the error.

* and / is working OK, the vector is supposed to be multiplied/divided by scalar.

1 Answer 1

1

Try this instead:

%i(- +).each do |op|
  define_method(op) do |v|
    @coords = @coords.zip(v.coords).map { |a, b| a.send(op, b) }
    self
  end
end

You want to zip the array, so calling coords on v makes that work. Also, map performs the given block and returns the collected results, you were discarding them.

Are you aware that Ruby has a Vector class?

2.1.5 :001 > require 'matrix'
 => true 
2.1.5 :002 > a = Vector[1,2,3,4]
 => Vector[1, 2, 3, 4] 
2.1.5 :003 > b = Vector[1,1,1,1]
 => Vector[1, 1, 1, 1] 
2.1.5 :004 > a - b
 => Vector[0, 1, 2, 3] 
2.1.5 :005 > a * 3
 => Vector[3, 6, 9, 12] 
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, I'm aware. However I need to keep this as simple as possible, hence the custom class. Your code works as intended, thank you very much!
Glad I could help, though I'm confused how defining your own classes keeps things simple!
one small question - I can't find a substitute for my shift_right! method in the default Ruby Vector class. What is the proper way to do this? vec.to_a, then shift/pop on an array and finally copy the modified array to my Vector?
Probably the easiest way, yeah. You add that method to the built in Vector class too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.