1

I want to achieve something like below. Defining method names based on array arguments and Call them.

arr = ['alpha', 'beta', 'gamma']

arr.each { |role|
  # If the method already exists don't define new
  if ! method_exist? "init_#{role}"
    define "init_#{role}"
      p "I am method init_#{role}"
    end
}

init_beta
init_gamma

Edit: If such a method already exists, don't define a new method.

1 Answer 1

1

Do as below :

arr = ['alpha', 'beta', 'gamma']

arr.each do |role|
  # this code is defining all the methods at the top level. Thus call to 
  # `method_defined?` will check if any method named as the string argument 
  # is already defined in the top level already. If not, then define the method.
  unless self.class.private_method_defined?( "init_#{role}" )
    # this will define methods, if not exist as an instance methods on 
    # the top level.
    self.class.send(:define_method, "init_#{role}" ) do
      p "I am method init_#{role}"
    end
  end
end

init_beta # => "I am method init_beta"
init_gamma # => "I am method init_gamma"

Look at the documentation of private_method_defined and define_method.

Note : I have used private_method_defined?, as on top level, all instance method you will be defining ( using def or define_method in the default accessibility level ), become as private instance methods of Object. Now as per your need you can also check protected_method_defined? and public_method_defined? accordingly.

Sign up to request clarification or add additional context in comments.

1 Comment

I am getting error "undefined method `method_defined?' for main:Object (NoMethodError)". Ruby version is 'ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]'

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.