Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I found a method definition in the github API v3, I don't know the meaning of the args=(not_set = true).

Can you show me some examples of the usage? 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
like image 459
hbin Avatar asked Feb 17 '23 01:02

hbin


2 Answers

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

Rather, the important question is why would someone go to this trouble? After all, the much simpler alternative usually works just fine:

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

However, that approach does not allow you to distinguish these two calls:

arguments()
arguments(nil)

If that distinction matters, you could use an approach like the one in the code you posted.

like image 144
FMc Avatar answered Feb 23 '23 21:02

FMc


the args setter method will only be triggered if you pass no data.

If you do:

arguments("foo")

Then:

  • args #=> "foo"
  • not_set #=> nil which is falsy

If you do:

arguments()

Then:

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

To be short: it's a pretty neat way to check if one arg has really been set.

like image 22
apneadiving Avatar answered Feb 23 '23 21:02

apneadiving