Reputation: 63
Consider the following Ruby Code:
def f1(p1, p2: nil, p3: nil)
puts "Parameter 1: #{p1}"
puts "Parameter 2: #{p2}"
puts "Parameter 3: #{p3}"
end
def f2(p1, p2: nil, p3: nil)
f1(p1, p2, p3)
end
# This will throw error ArgumentError: wrong number of arguments (3 for 1)
f2("Hi")
In the above code, my problem is I need to list the parameters in both f1 and f2 (user requirement). At the same time I should enable the named parameters for the user (because the 3 parameters can become 30 parameters with most of them having a default value)
Has anyone come across this issue?
Upvotes: 2
Views: 451
Reputation: 6100
You used named parameters, you have to specify them explicitly.
...
def f2(p1, p2: nil, p3: nil)
f1(p1, p2: p2, p3: p3) # specify p2 and p3
end
f2("Hi")
When you call f1
you have to specify explicitly p2
and p3
if you want to define them
Check the official documentation or some third-party resources about this
def foo(arg1 = 1, arg2:, arg3: nil)
puts "#{arg1} #{arg2} #{arg3}"
end
foo(arg2: 'arg2')
# Will display
# 1 arg2
foo('arg1_defined', arg2: 'arg2')
# WIll display
# arg1_defined arg2
Note: Also named arguments do not have to follow order, you can place them at any order you want, but after other arguments
foo(arg3: 'arg3_with_value', arg2: 'arg2_val')
# 1 arg2_val arg3_with_value
foo(arg3: 'arg3_val', 10)
# SyntaxError: unexpected ')', expecting =>
# they have to be after not-named arguments
Upvotes: 4