Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

320
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!