Search code examples
rubyquaternions

How to define a class method :[] when using class_eval


I am using the quaternion gem and want to define a class method for the :[] operator that creates a new Quaternion from an array. I have tried

Quaternion.class_eval do
  def self.[ary]
    Quaternion.new(*ary)
  end
end

but this gives a syntax error. How do I do this?


Solution

  • The method's name is [], but it still takes its argument list in the usual way

    def self.[](ary)
      ...
    end
    

    Then you call it as Quaternion[ary]