Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

Mixing keyword with regular arguments in Ruby?

Ruby 2.0 supports keyword arguments. I was wondering, what are the 'rules' for mixing regular with keyword arguments? Something like this would not work:

def some_method(a: 'first', b: 'second', c)
  [a, b, c]
end

but this will:

def some_method(c, a: 'first', b: 'second')
  [a, b, c]
end

So why does putting a regular argument before the keyword arguments (and not after) works?

Is there some reference on the web on this (mixing keyword and regular arguments)? I can't seem to find any.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...