What is the behavior when using both positional and keyword arguments in Ruby?

The order is as follows:

  • required arguments
  • arguments with default values (arg=default_value notation)
  • optional arguments (*args notation, sometimes called “splat parameter”)
  • required arguments, again
  • keyword arguments
    • optional (arg:default_value notation, since 2.0.0)
    • intermixed with required (arg: notation, since 2.1.0)
  • arbitrary keyword arguments (**args notation, since 2.0.0)
  • block argument (&blk notation)

For example:

def test(a, b=0, *c, d, e:1, f:, **g, &blk)
  puts "a = #{a}"
  puts "b = #{b}"
  puts "c = #{c}"
  puts "d = #{d}"
  puts "e = #{e}"
  puts "f = #{f}"
  puts "g = #{g}"
  puts "blk = #{blk}"
end

test(1, 2, 3, 4, 5, e:6, f:7, foo:'bar') { puts 'foo' }
# a = 1
# b = 2
# c = [3, 4]
# d = 5
# e = 6
# f = 7
# g = {:foo=>"bar"}
# blk = #<Proc:0x007fb818ba3808@(irb):24>

More detailed information is available from the official Ruby Syntax Documentation.

Leave a Comment