joanx737
joanx737

Reputation: 367

How to ignore extra arguments in ruby

I'm writing a script that passes in several arguments to a set of pg queries. Some of these queries take 2 date arguments, and some only take 1. I'm wondering if there's a way for the query to ignore any 'extra' date arguments that are passed to it.

E.g. this command runs for every query in DailyQueries:

DailyQueries.send(query_name, conn, date_1, date_2)

I have some queries that are structured as such:

DailyQueries.tot_students(conn, date)

While others as:

DailyQueries.fact_practice_tot_sessions(conn, start_date, end_date)

And would ideally the former to run even if it's getting 2 date arguments passed in. Right now I'm getting this error:

wrong number of arguments (3 for 2) (ArgumentError)

Upvotes: 0

Views: 2577

Answers (1)

Mircea
Mircea

Reputation: 10566

def zoo(*args)
  puts args.inspect
end

you can check the number of args and accept or reject the call based on what your expectations are.

irb(main):001:0> def zoo(*args)
irb(main):002:1> puts args.inspect
irb(main):003:1> end
=> nil
irb(main):004:0> zoo
[]
=> nil
irb(main):005:0> zoo 1
[1]
=> nil
irb(main):006:0> zoo 1,2,3,4,5
[1, 2, 3, 4, 5]

Also take a look at: http://ruby-doc.org/core-2.2.0/Method.html#method-i-arity and http://ruby-doc.org/core-2.2.0/Method.html#method-i-curry

In case you don't control the code directly: You could write a wrapper that checks the arrity and dispatches the correct number of args or if you're feeling lucky you can try to monkey patch the method to support this behavior.

Upvotes: 1

Related Questions