Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

321
Vistas
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?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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]

over 4 years ago · Santiago Trujillo Denunciar

0

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)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda