본문 바로가기

TIL/RUBY

Argument

default argument

 

def aMethod( a=10, b=20, c=100, *d )
	return a, b, c, d
end

def anotherMethod( greeting="Hello", name="friend" )
	return "#{greeting}, #{name}"
end

p( aMethod )               # result : [10, 20, 100, []]
p( aMethod( 1,2 ) )        # result : [1, 2, 100, []]
p( aMethod( 1,2,3 ) )      # result : [1, 2, 3, []]
p( aMethod( 1,2,3,4,6 ) )  # result : [1, 2, 3, [4, 6]]

 

위와 같은 식으로 디폴트값을 지정할 수 있다. 또한 기존에 선언한 매개변수보다 더 많은 값을 넘기고 싶다면 *d 의 형태로 작성 가능하다. c위치 다음에 오는 매개변수들은 배열에 담겨 리턴되게 된다. 

if you want to be able to pass more args than actually declared in the method, you can put an argument name following an asterisk as shown above. it will bundle up any excess args into array

 

 

** Udemy의  「Advanced Ruby Programming: 10 Steps To Mastery」를 보고 작성하였습니다.

'TIL > RUBY' 카테고리의 다른 글

루비 구조와 해석(interpretation)  (0) 2021.03.05
exception error handling  (0) 2021.01.24
Encapsulation and Information Hiding  (0) 2021.01.23
class method  (0) 2020.12.09
Symbol  (0) 2020.12.05