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

Time:09-16

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?

CodePudding user response:

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]

CodePudding user response:

So long story short to be able to make use of Quaternion[arg] you want to define it like below

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

interesting is, why does it work? Well it's syntactic sugar that ruby has

doing foo[bar] is the same as foo.[](bar)

foo[bar]=baz is the same as foo.[]=(bar, baz)

and a b is actually a. (b)

If you want to define it, it will look like this:

def [](key)
  ...
end

def []=(key, value)
  ...
end

def  (arg)
  ...
end

It's because method names in ruby can have special characters.

If you are interested in how internally it gets tokenized and parsed you can read Ruby Under Microscope which is a great introduction to the subject. There is also this free book I've found which also touches on the topic -> https://ruby-hacking-guide.github.io/ (check chapter 8 section Method Calls)

  • Related