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

162
Views
Simultaneously creating instance and class methods with the same name in a ruby class

Is there a way for me to simultaneously create a class and an instance method in a ruby class that have the same name? I have a version of this created in the class Foo

class Foo 
   def self.bar
      "hello world" 
   end

   def bar
     self.class.bar
   end
end

While this works, is there a more elegant way of achieving this? Right now, I would have to duplicate ~10 methods as instance and class methods.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

you can use Ruby's Forwardable like this:

# in foo.rb
class Foo
  extend Forwardable

  def_delegators :Foo, :bar, :baz, :qux

  def self.bar
    "hello bar"
  end

end

then

> Foo.bar #=> "hello bar"
> Foo.new.bar #=> "hello bar"

You can also use method_missing like this:

class Foo
  DelegatedMethods = %i[bar baz qux]

  def method_missing(method)
    if DelegatedMethods.include? method
      self.class.send method
    else
      super
    end
  end

  def self.bar
    "a man walked into a bar"
  end
end
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!