Self-Improvement

기초 (인자, 읽기 쓰기, 메소드, 배열, 키와 값, nil, 상수(심볼), IF문, While문) 본문

프로그래밍/Ruby

기초 (인자, 읽기 쓰기, 메소드, 배열, 키와 값, nil, 상수(심볼), IF문, While문)

JoGeun 2020. 8. 14. 18:00

이름으로 용도를 구분할 수 있는 표

 지역 변수  name, fish_and_chips, _x, _26
 인스턴스 변수  @name, @point_1, @x, @_
 클래스 변수  @@total, @@symtab, @@x_pos
 전역 변수  $debug, $CUSTOMER, $_Golbal
 클래스 이름  String, MyClass
 상수 이름  FEET_PER_MILE, DEBUG

 

인자 읽고 쓰기

인자의 길이와 "p", "puts"로 쓰일때의 다른점

1
2
3
4
puts "arguments #{ARGV.size}"
p ARGV
p ARGV[3]
puts ARGV
cs

 

 

읽어들여 쓰기 예제코드

"p", "puts", "print" 차이

1
2
3
4
str=gets
str
puts str
print str
cs

 

 

메소드 정의 및 호출 예제코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1. 기본 메소드 정의
def say_goodnight(name)
    result="good night,"+name
    return result
end
 
puts say_goodnight("jo")
puts say_goodnight("geun")
 
 
2. {}을 사용할 시엔 return 문이 없어도 된다.
def say_goodnight(name)
    result="good night, #{name.capitalize}"
end
 
puts say_goodnight("jo")
puts say_goodnight("geun")
cs

 

 

배열, 키와 값 선언, nil 예제 코드

nil은 아무것도 아님을 표현하는 하나의 객체이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1. 배열 선언
a=[1'cat'3.14]
puts "The first element is #{a[0]}"
a[2]=nil 
puts "The array is now #{a.inspect}"
 
2. %w로 배열 선언
a=%w{ant bee cat dog elk}
puts a[0]
puts a[3]
 
3. 키, 값 선언 
inst_section = {
    'cello' => 'string',
    'drum' => 'percussion',
    'violin' => 'string'
}
p inst_section['cello']
p inst_section['drum']
p inst_section['oboe'# p는 nil까지 출력을 해준다.
 
cs

 

 

nil 대신 기본값 설정 예제 코드

키에 해당하는 객체가 없을 때는 기본적으로 nil을 반환하게 되며 nil 대신에 기본값을 설정할 수 있다.

1
2
3
4
test=Hash.new(0)
p test['ruby']
p test['ruby']=test['ruby']+1
p test['ruby']
cs

 

상수(심벌) 예제 코드

상수란 값이 변하지 않는 변수?를 뜻한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#1. 상수는 ":"을 사용한다.
test={
    :cello => 'string',
    :drum => 'percussion'
}
p test[:cello]
p test[':cello']
 
#2. 좀 더 간략하게 표현
test2={
    cello: 'string',
    drum: 'percussion'
}
p test2[:cello]
p test2['cello']
cs

 

 

IF 문 예제 코드

다른 프로그래밍의 IF문과 별다를건 없다.

보기 편하게 위해선 then을 써도 되지만 생략할 수 있다.

1
2
3
4
5
6
7
8
9
10
today=Time.now
p today
 
if today.saturday?
    p "A"
elsif today.sunday?
    p "B"
else
    p "C"
end
cs

 

 

1
2
3
4
5
6
7
radiation=0
if radiation < 3000
    p "A"
end
 
# 위 예제를 한줄로
"A" if radiation < 3000
cs

 

 

While문 예제 코드

while문도 어려울건 없다.

1
2
3
4
5
6
7
num=0
weight=0
 
while weight<100 and num<=5
    num+=1
    p num
end
cs

 

 

1
2
3
4
5
6
7
8
9
10
a=4
while a <1000
    a=a*a
end
p a
 
#위 while문을 한 줄로
b=4
b=b*while b < 1000
p b
cs