[ruby-talk:444085] Re: A simple question about arguments

def tt (x=123) puts x end => :tt
tt 123 => nil
tt(456) 456 => nil
The code above is the default argument I know. But this one,
def tt2 (x:123) puts x 1> end => :tt2
tt2 123 => nil
tt2(456) Traceback (most recent call last): 5: from /usr/bin/irb:23:in `<main>' 4: from /usr/bin/irb:23:in `load' 3: from /Library/Ruby/Gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>' 2: from (irb):10 1: from (irb):6:in `tt2' ArgumentError (wrong number of arguments (given 1, expected 0))
As you see it fails. But the following calling could work.
tt2(x:456) 456 => nil
tt2(:x=>456) 456 => nil
what's the trick behind it? Thanks & regards, Henry

On December 18, 2022 1:09:51 AM UTC, Henry R via ruby-talk <ruby-talk@ml.ruby-lang.org> wrote:
def tt2 (x:123) puts x end
tt2 123 tt2(456) ArgumentError (wrong number of arguments (given 1, expected 0)) tt2(x:456) 456 tt2(:x=>456) 456
what's the trick behind it?
"x" in tt2 is a keyword argument: https://docs.ruby-lang.org/en/3.0/syntax/methods_rdoc.html#label-Keyword+Arg... https://thoughtbot.com/blog/ruby-2-keyword-arguments https://www.bigbinary.com/blog/ruby-2-7-deprecates-conversion-of-keyword-arg...
participants (2)
-
Frank J. Cameron
-
Henry R