Can I do 'alias' just for instance methods? (SOLVED)

(SOLUTION added at the end of the posting)

Say someone is giving me a class

class Foo
  def self.bar
  end
  def baz
  end
end

Without touching the original code, I would like to add an instance
method ‘bar’, which behaves exactly like ‘baz’. I can do it like this:

class Foo
  def bar
    self.baz
  end
end

Semantically, this is fine, but it causes one extra redirection step. I
would like to use alias

class Foo
   alias bar baz
end

but this doesn’t work, because ‘bar’ is already a class method.

Any solution for this?

UPDATE: I found the solution for this. It was actually easy - Ruby keeps
of course class methods and instance methods apart, and I can simply do
a

class Foo
  alias :bar :baz
end

and everything works fine. I should have tried it in the beginning, but
I was so sure that it would not work…

I think this should work:

class << Foo
alias :baz :bar
end

Joel P. wrote in post #1181234:

I think this should work:

class << Foo
alias :baz :bar
end

No, it doesn’t. This would create baz as an alias for the class method
bar.

No, it doesn’t. This would create baz as an alias for the
class method bar.

Does not matter.

You can use .instance_eval and .class_eval to modify essentially
everything, even at runtime.

I often do something like this in my classes:

self.instance_eval { alias foo bar }

Simply because I like this more than the

class << Foo

usage.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs