Ruby metaprogramming - getting method names and parameter information for a class

I want to get class methods in an object. See the following example. I have a user.rb class

class User
  def say_name

  end

  def walk(p1)

  end

  def run(p1, p2)

  end
end

and I wrote the following code

require 'user.rb'

a = User.new

arr = a.public_methods(all = false)

The above code will return the method name. But my question is: I want to get the method name with parameters

def def run(p1, p2)

end

I want to get the method name ("run") and its parameter names (p1, p2) or the number of parameters (2)

Can someone help me, thanks in advance

amuses

Sameera

+3
source share
3 answers
User.new.method(:run).arity   # => 2
+5
source

if you need options then http://github.com/rdp/arguments is your friend

+1
source

:

User.new.method(:run).parameters # => [[:req, :p1], [:req, :p2]]

req , . , :

  • def run(p1 = nil) = > [[:opt, :p1]]
  • def run(*p1) = > [[:rest, :p1]]
  • def run(&p1) = > [[:block, :p1]]
  • def run(p1:) = > [[:key, :p1]]
  • def run(p1: nil) = > [[:keyopt, :p1]]
  • def run(**p1) = > [[:keyrest, :p1]]
0

Source: https://habr.com/ru/post/1768585/


All Articles