Ruby/Method/Variable Number Arguments
Материал из Wiki.crossplatform.ru
Версия от 17:55, 13 сентября 2010; ViGOur (Обсуждение | вклад)
Содержание |
A variable number of arguments stored in an array.
def num_args( *args ) length = args.size label = length == 1 ? " argument" : " arguments" num = length.to_s + label + " ( " + args.inspect + " )" num end puts num_args puts num_args(1) puts num_args( 100, 2.5, "three" )
Mixed parameters and varied length parameter
#!/usr/bin/env ruby def two_plus( one, two, *args ) length = args.size label = length == 1 ? " variable argument" : " variable arguments" num = length.to_s + label + " (" + args.inspect + ")" num end puts two_plus( 1, 2 ) puts two_plus( 1000, 3.5, 14.3 ) puts two_plus( 100, 2.5, "three", 70, 14.3 )
Passing a Variable Number of Arguments
def putter(first_word, *others) puts first_word + " " + others.join(" ") end putter "Hello", "from", "Ruby."
prefixing the array with an asterisk
array = ["there ", "AAA"] def putter(first_word, second_word, third_word) puts first_word + " " + second_word + " " + third_word end putter "Hello ", *array
Variable Arguments
def num_args( *args ) length = args.size label = length == 1 ? " argument" : " arguments" num = length.to_s + label + " ( " + args.inspect + " )" num end puts num_args puts num_args(1) puts num_args( 100, 2.5, "three" )