0

Let's say I had a class and I wanted to be able to call the same method on the class itself and an instance of that class:

class Foo
  def self.bar
    puts 'hey this worked'
  end
end

This lets me do the following:

Foo.bar #=> hey this worked

But I also want to be able to do:

Foo.new.bar #=> NoMethodError: undefined method `bar' for #<Foo:0x007fca00945120>

So now I modify my class to have an instance method for bar:

class Foo
  def bar
    puts 'hey this worked'
  end
end

And now I can call bar on both the class and an instance of the class:

Foo.bar #=> hey this worked
Foo.new.bar #=> hey this worked

Now my class Foo is 'wet':

class Foo
  def self.bar
    puts 'hey this worked'
  end

  def bar
    puts 'hey this worked'
  end
end

Is there a way to avoid this redundancy?

1 Answer 1

2

Have one method call the other. Otherwise, no, there is no way to avoid this "redundancy", because there is no redundancy. There are two separate methods that happen to have the same name.

class Foo
  def self.bar
    puts 'hey this worked'
  end

  def bar
    Foo.bar
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.