Inspecting Method Parameters in Ruby 2.2.3

Required Parameter

class Car
  def drive(speed)
  end
end

car = Car.new
method = car.method(:drive)

p method.parameters

This prints : [[:req, :speed]]. The :req symbol means required argument.

Optional Parameter

class Car
  def drive(speed, options = {})
  end
end

car = Car.new
method = car.method(:drive)

p method.parameters

This prints : [[:req, :speed], [:opt, :options]]. The :opt symbol means option parameter.

Splat Operator

class Car
  def drive(speed, options = {}, *args, &blk)
  end
end

car = Car.new
method = car.method(:drive)

p method.parameters

This prints [[:req, :speed], [:opt, :options], [:rest, :args], [:block, :blk]]. The :rest symbol is for variable length argument list.

Keyword Arguments

class Car
  def drive(direction:, speed: :high, **args)
    p direction
  end
end

car = Car.new
method = car.method(:drive)

p method.parameters

This prints [[:keyreq, :direction], [:key, :speed], [:keyrest, :args]]

Summary


In this article we saw how we can inspect method parameters in Ruby. For a practical application of this concept, check out action_args Rails plugin.

Reference


Ruby 2 Methodology by Akira Matsuda


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.