How to check if a method is defined in ruby?

There are many different ways of doing this, I will put 2 examples of how you can be sure if you had a method declared on a specific class.

Public and Protected Methods:

For example

class User  
  def user_name
    @user.name
  end
end

User.method_defined? 'user_name' # true  
User.method_defined?  :user_name # true  

What else?

class User  
  ...  
  protected

  def user_name
    @user.name
  end
end

User.method_defined? 'user_name' # true  
User.method_defined?  :user_name # true  
Private Methods:

For example:

class User  
  def check_private
    self.class.private_method_defined? 'user_name'
  end  

  private

  def user_name
    @user.name
  end
end  

You can find more info here:

method_defined?

private_method_defined?

That's all folks!

Victor Velazquez

Coder, Musician, Startups, Passionate Dancer & Life Lover. Software Engineer at MagmaLabs, Co-founder of Web Dev Talks, Co-founder of Voltaire, Co-founder of Paqkit, Ex-co-founder of Zaznova.

Subscribe to The zazvick's blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!