Ruby Quiz #1 by jgn on Thursday, February 6, 2014 in Ruby

The rules: If you have to look stuff up or Google for it, you may post comments but not a solution. If you have a solution in your brain and can solve it without consulting authorities, post your solution.

You have a class like this and an example of its usage:

class Vector
  def initialize(x, y)
    @x, @y = x, y
  end


  def *(value)
    self.class.new(@x * value, @y * value)
  end


  def to_s
    "#{@x}, #{@y}"
  end
end


v = Vector.new(3, 5)
puts v
puts v * 3

Output:

3, 5
9, 15

You would like to make the #* method commutative, so that the following script

puts v * 3
puts 3 * v

produces

9, 15
9, 15

Add one method to the Vector class to produce this result. The method body should have only one line.

comments powered by Disqus