Metoda Ruby z maksymalną liczbą parametrów


Mam metodę, która powinna przyjmować maksymalnie 2 argumenty. Jego kod wygląda następująco:
def method (*args)
if args.length < 3 then
puts args.collect
else
puts "Enter correct number of arguments"
end
end

Czy istnieje bardziej elegancki sposób określenia tego?
Zaproszony:
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Masz kilka opcji, w zależności od tego, jak chcesz, aby metoda była szczegółowa i ścisła.
# force max 2 args
def foo(*args)
raise ArgumentError, "Too many arguments" if args.length > 2
end# silently ignore other args
def foo(*args)
one, two = *args
# use local vars one and two
end# let the interpreter do its job
def foo(one, two)
end# let the interpreter do its job
# with defaults
def foo(one, two = "default")
end
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

jeśli maksimum to dwa argumenty, po co w ogóle zawracać sobie głowę takim operatorem splat? Po prostu bądź szczery. (chyba że istnieje jakieś inne ograniczenie, o którym nam nie powiedziałeś).
def foo(arg1, arg2)
# ...
end

Lub...
def foo(arg1, arg2=some_default)
# ...
end

Lub nawet...
def foo(arg1=some_default, arg2=some_other_default)
# ...
end
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Lepiej zgłoś błąd. Jeśli argumenty są błędne, to jest to poważny problem, który nie powinien pojawić się w twoich skromnych
puts
.
def method (*args)
raise ArgumentError.new("Enter correct number of arguments") unless args.length < 3
puts args.collect
end

Aby odpowiedzieć na pytania, Zaloguj się lub Zarejestruj się