What does the parameter "args = (not_set = true)" mean in ruby?

I found a method definition in github API v3 , I do not know the value of args=(not_set = true) .

Can you show me some usage examples? thanks.

 # Acts as setter and getter for api requests arguments parsing. # # Returns Arguments instance. # def arguments(args=(not_set = true), options={}, &block) if not_set @arguments else @arguments = Arguments.new(self, options).parse(*args, &block) end end 
+4
source share
3 answers

The set args method is run only when there is no data.

If you do:

 arguments("foo") 

Then:

  • args #=> "foo"
  • not_set #=> nil , which is false

If you do:

 arguments() 

Then:

  • args #=> nil
  • not_set #=> true

In short: this is a pretty simple way to check if a single argument is actually set.

+2
source

An interesting question is not how the code works: if args not passed, the not_set = true code will be evaluated.

Rather, the important question is: why would someone go to this problem ? After all, a much simpler alternative usually works very well:

 def arguments(args = nil) if args.nil? ... else ... end end 

However, this approach does not distinguish between these two calls:

 arguments() arguments(nil) 

If this difference matters, you can use an approach like the one you posted.

+4
source

According to this blog , the default value for a parameter may be the result of an executed expression. So what they do is set the flag in the expression (not_set = true) and use it as the default value. Thus, in cases where "args" is not specified, the expression (not_set = true) will be evaluated.

Read the link for really interesting examples .

+2
source

Source: https://habr.com/ru/post/1489311/


All Articles