Named parameters in Ruby 2

后端 未结 8 1751
闹比i
闹比i 2020-12-13 13:28

I don\'t understand completely how named parameters in Ruby 2.0 work.

def test(var1, var2, var3)
  puts \"#{var1} #{var2} #{var3}\"
end

test(var3:\"var3-ne         


        
相关标签:
8条回答
  • 2020-12-13 14:12

    Firstly, the last example you posted is misleading. I totally disagree that the behavior is similar to the one before. The last example passes the argument hash in as the first optional parameter which is a different thing!

    If you do not want to have a default value, you can just use nil.

    If you want to read a good writeup, see "Ruby 2 Keyword Arguments".

    0 讨论(0)
  • 2020-12-13 14:13

    This is present in all the other answers, but I want to extract this essence.

    There are four kinds of parameter:

                 Required     Optional
    Positional | def PR(a)  | def PO(a=1) |
    Keyword    | def KR(a:) | def KO(a:1) |
    

    When defining a function, positional arguments are specified before keyword arguments, and required arguments before optional ones.

    irb(main):006:0> def argtest(a,b=2,c:,d:4)
    irb(main):007:1> p [a,b,c,d]
    irb(main):008:1> end
    => :argtest
    
    irb(main):009:0> argtest(1,c: 3)
    => [1, 2, 3, 4]
    
    irb(main):010:0> argtest(1,20,c: 3,d: 40)
    => [1, 20, 3, 40]
    

    edit: the required keyword argument (without a default value) is new as of Ruby 2.1.0, as mentioned by others.

    0 讨论(0)
提交回复
热议问题