2. What is the Ruby?
• meaning reading and writing Ruby is really easy—
• it looks a lot like regular English!High-level
• meaning you don't need a compiler to write and run Ruby.InterpretedInterpreted
• everything in Ruby is an object.Object-oriented
• Marts design a language that emphasized human needs over tho
se of the computer, which is why Ruby is so easy to pick up.Easy to use
4. Who made the Ruby?
• 마츠모토 유키히로
• 프로그래머
• 마츠모토 유키히로 는 루비를 개발한 프로그래머이다.
일본 오사카 부 태생. 고등학교까지 독학으로 프로그
래밍을 익혔으며, 쓰쿠바 대학교 정보학부를 나와,
• 시마네대학 대학원에서 박사과정을 취득했다. 2006
년 현재, 시마네 현에서 오픈소스 관련 회사인 네트워
크 응용통신 연구소의 특별 연구원으로 재직하고 있
다. 마츠모토는 결혼하여 4명의 아이들이 있다.
• 출생: 1965년 4월 14일 (49세), 일본 오사카 부 오사카 시
• 학력: 쓰쿠바 대학
5. Why made the Ruby?
• 마츠모토 유키히로 : 프로그램을 짜는 것이
쉬워즈는 것 뿐만 아니라,
• 프로그래머가 즐거워지도록 설계했습니다.
• 저는 많은 프로그래밍 언어를 알지만, 그 어느것에서도 만
족할 수 없었습니다. 제가 기대한 것 보다 보기 흉하거나,
거칠거나, 복잡하거나, 너무 간단했습니다.
• 그래서 스스로 만졸할만한 자신만의 언어를 만들고 싶었습
니다. 자신을 위한 언어라서 어디가 가려운 곳인지 잘 알고
있었습니다. 깜짝놀란 것은 이세상에는 저처럼 느끼는 프로
그래머가 수없이 많다는 것입니다.
• 루비를 개발하면서 프로그래밍을 더 빠르고 ‘쉽게’ 하는데
집중했습니다.
10. Everything is object in Ruby
• (※ 주석은 #으로 시작하고 =>는 명령어를 실행했을때 반환되는 값을 나타냅니다.)
1.class #=>Fixnum
0.0.class #=>Float
True.class #=>TrueClass
False.class #=>FalseClass
Nil.class #=>NilClass
False.class #=>FalseClass
Nil.class #=>NilClass
1.class #=>Fixnum
Method (메소드)
11. Method in Ruby
• Method form in ruby
def (parameter1, parameter2, parameter3…)
Doing Something
end
• Parentheses are usually optional in Ruby.
• 보통 parameter 혹은 리턴의 대상이 한 개일 때 생략한다.
end
12. Method in Ruby
• Implicit Return
• Parentheses are usually optional in Ruby.
• 보통 parameter 혹은 리턴의 대상이 한 개일 때 생략한다.
Interpolation 보간법
13. Interpolation
• Interpolation
• Interpolation allows Ruby code to appear within a string. The result of evaluating t
hat code is inserted into the string:
• "1 + 2 = #{1 + 2}" #=> "1 + 2 = 3"
#{expression}
14. The end of the sentence
• Usually, Every sentence should be ended by semi-colon in ‘Java’ or ‘C‘
• But in Ruby, Don’t care about it.
불완전한문장(이어짐)
완전한문장(종료)완전한문장(종료)
문장연결
15. Interpolation
• Interpolation
• Interpolation allows Ruby code to appear within a string. The result of evaluating t
hat code is inserted into the string:
• "1 + 2 = #{1 + 2}" #=> "1 + 2 = 3"
#{expression}
16. Dynamic Typing
• Ruby is dynamically typed: the type of a variable is generally not inferable until
runtime. So s=5 can follow s=” foo” in the same block of code.
• Because variables do not have types.
17. Dynamic Typing
• Ruby is dynamically typed: the type of a variable is generally not inferable until
runtime. So s=5 can follow s=” foo” in the same block of code.
• Because variables do not have types.
18. Dynamic Typing
• Ruby is dynamically typed: the type of a variable is generally not inferable until
runtime. So s=5 can follow s=” foo” in the same block of code.
• Because variables do not have types.
19. Every Operation is a Method Call
• every operation is a method call, note that even basic math operations
• such as +, *, = = (equality comparison) are ‘syntactic sugar’ for method calls
20. Every Operation is a Method Call
• every operation is a method call, note that even basic math operations
• such as +, *, = = (equality comparison) are ‘syntactic sugar’ for method calls
• syntactic sugar (사람이 이해하고 쉽고 표현하기 쉽게 컴퓨터 언어를 디자인해 놓은 문맥)
• (computing) Additions to a computer language that make code easier for humans
to read or write, but that do not change the functionality or expressiveness of the
language. -Wikipidea
21. Every Operation is a Method Call
• 객체가 갖고 있는 것
• 클래스 상속 구조
• 객체의 속성과 메소드
• 메소드에 대한 정보
리플렉션 (Reflection)
루비와 같은 동적 언어의 많은 장점 중 하나는 인트로스페션(introspection)이 가능하다는 점이다.
즉 프로그램 스스로 자기자신의 생긴 모양을 살펴 볼 수 있다는 의미.
22. Every Operation is a Method Call
• 원하는 클래스의 객체 사용현황파악
• (※Fixnum,Symbol,true,nill등 즉시 값을 갖는 객체는 사용불가)
• ObjectSpace.each_object(Some_class) {|x| p x}
리플렉션 (Reflection)
23. Every Operation is a Method Call
• 인스턴스내의 메소드 확인
instance name.respond_to(“method name”)
리플렉션 (Reflection)
24. Every Operation is a Method Call
• 객체(인스턴스)에 대해서 살펴보는 것은 리플렉션의 한 측면 일 뿐
• 전체 그림을 얻기 위해서는 클래스에 대해서도 알아야 한다.
리플렉션 (Reflection)
25. Every Operation is a Method Call
• 객체(인스턴스)에 대해서 살펴보는 것은 리플렉션의 한 측면 일 뿐
• 전체 그림을 얻기 위해서는 클래스에 대해서도 알아야 한다.
리플렉션 (Reflection)
26. Every Operation is a Method Call
• “if something looks like a duck and quacks like a duck, it might as well be a duck.”
• “오리처럼 보이고, 오리처럼 울면, 그건 오리일 것이다.”
• 객체의 타입은 클래스에 의해서가 아니라, 무엇을 할 수 있는가에 의해 결정되는 것이다.
Duck Typing ; ( Viewpoint, philosophy )
EverythingEverything
is object
in Ruby.
Reflection.
Typing
Duck
Typing
27. Every Operation is a Method Call
• “if something looks like a duck and quacks like a duck, it might as well be a duck.”
• “오리처럼 보이고, 오리처럼 울면, 그건 오리일 것이다.”
• 객체의 타입은 클래스에 의해서가 아니라, 무엇을 할 수 있는가에 의해 결정되는 것이다.
Duck Typing ; ( Viewpoint, philosophy )
치킨
배달원이
겠지?
치킨만 받으면 OK! 치킨만 고객이 받으면 OK!
28. Every Operation is a Method Call
• “if something looks like a duck and quacks like a duck, it might as well be a duck.”
• “오리처럼 보이고, 오리처럼 울면, 그건 오리일 것이다.”
• 객체의 타입은 클래스에 의해서가 아니라, 무엇을 할 수 있는가에 의해 결정되는 것이다.
Duck Typing ; ( Viewpoint, philosophy )
Fileopen.class 파일열기class FileManagement{class FileManagement{
class FileManagement{
public void main(String Args[])
Fileopen.class
Modify.class
Save.class
파일열기
수정하기
저장하기
class FileManagement{
public void main(String Args[])
if ( ! Fileopen 의 인스턴스?){…}
if ( ! Modify 의 인스턴스?){…}
if ( ! Save 의 인스턴스?){…}
…
}
class FileManagement{
public void main(String Args[])
if ( ! Fileopen 의 기능이 있는가?){…}
if ( ! Modify 의 기능이 있는가?){…}
if ( ! Save 의 기능이 있는가?){…}
…
}
if ( ! Fileopen 의 기능이 있는가?){…}
if ( ! Modify 의 기능이 있는가?){…}
if ( ! Save 의 기능이 있는가?){…}
루비는 Dynamic typing으로 인해 변수
의 타입은 가변적이다.
따라서 사용자가 올바르게, 상황에 맞춰
사용하면 된다.
오리처럼 보이고, 오리처럼 울면된
다. 자유방임주의(laissez-faire)
…
}
29. Every Operation is a Method Call
Duck Typing ; ( Viewpoint, philosophy )
클래스 타입 비교 - JAVA, C#
30. Every Operation is a Method Call
Duck Typing ; ( Viewpoint, philosophy )
객체 보유 함수(메소드) 기준 검사
31. Every Operation is a Method Call
Duck Typing ; ( Viewpoint, philosophy )
자유방임주의스타일 (laissez-faire)
32. Every Operation is a Method Call
• lets us define new code at runtime.
메타프로그래밍(metaprogramming)
42. Blocks and Yield
Def call_back
puts “Start of method”
yield
yield
puts “End of method”
End
Result :
Start of method
In the block
In the block
End of method
Yield : 넘겨주다, 양도하다
인스턴스명.메소드명(argument) {|parameter| doing something.}
End
Call_block {puts “In the block”}
Def call_block
yield(“hello”, 99)
End
call_block {|str, num| …} blockblock
44. Blocks and Yield
Yield : 넘겨주다, 양도하다
인스턴스명.메소드명(argument) {|parameter| doing something.}
blockblock
Block을 통해 inner function 또는 inner method를 구현 할 수 있다.
50. Proc & Lambda : Savable Blocks!
Proc Lambda
Checking Arguments X O
if you pass it the wrong number of
arguments
Ignore
andassign nil
throw an error
control back to the calling method X O
즉시종료 통제권반환
51. closure
closure : 클로저(closure)는 내부함수가 외부함수의 맥락(context)에 접근할 수 있는 것을 가르킨다.
내부함수는 외부함수의 지역변수에 접근 할 수 있는데,
외부함수의 실행이 끝나서 외부함수가 소멸된 이후에도 내부함수가 외부함수의 변수에 접근 할 수 있다.
이러한 메커니즘을 클로저라고 한다.
1
2
3
4
5
6
function factory_movie(title){
return {
get_title : function (){
return title;
실행결과
Ghost in the shell -> Matrix -> 공각기동대 -> Matrix
Javascript
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
return title;
},
set_title : function(_title){
title = _title
}
}
}
ghost = factory_movie('Ghost in the shell');
matrix = factory_movie('Matrix');
alert(ghost.get_title());
alert(matrix.get_title());
ghost.set_title('공각기동대');
alert(ghost.get_title());
alert(matrix.get_title());
52. closure
closure : 클로저(closure)는 내부함수가 외부함수의 맥락(context)에 접근할 수 있는 것을 가르킨다.
내부함수는 외부함수의 지역변수에 접근 할 수 있는데,
외부함수의 실행이 끝나서 외부함수가 소멸된 이후에도 내부함수가 외부함수의 변수에 접근 할 수 있다.
이러한 메커니즘을 클로저라고 한다.
함수(메소드) A
int var1 1) Test = 함수 A
2) Test 실행
return 함수(메소드) B
함수(메소드) B
print var1
2) Test 실행
3) 결과?
Var1이 나오는가 안나오는가?
Block
Proc
Lambda
54. closure
def multiply(m) test = multiply(2) -> 외부함수 변수대입def multiply(m)
n = m
return lambda{|data|data.collect{|x| x*n}}
end
test = multiply(2)
puts test.call([1,2,3])
test = multiply(2) -> 외부함수 변수대입
def multiply(2)
n = 2
return lambda{|data|data.collect{|x| x*2}}
end
puts test.call([1,2,3]) ->
lambda{|[1,2,3]|[1,2,3].collect{|x| x*2}}
Lambda 는 정의된 범위 밖에서 사용되고, 메서드 인수 n을
가두므로(Close Over) 클로저(Closure)라고 한다.
55. closure
Lambda 는 정의된 범위 밖에서 사용되고, 메서드 인수 n을
가두므로(Close Over) 클로저(Closure)라고 한다.
Private 변수처럼 이용하는 모습
- OOP에서 하나의 인스턴스와 유사하게 보인다.
59. Kinds of Variables
First letter Kinds Default value Example
Lowercase or _ Local variable
지역 변수
참조 전 대입 local_var
@ Instance variable
인스턴스 변수
Nil @instance_var
@@ Class variable 참조 전 대입 @@class_var@@ Class variable
클래스 변수
참조 전 대입 @@class_var
$ Grobal variable
전역 변수
Nil $global_var
Uppercase Constant
상수
참조 전 대입 CONSTANT_VAR
64. Modules & Mix-in
mix-in :
A mix-in is a set of related behaviors that can be added to any class.-
Fox, Armando; Patterson, David (2014-01-03). Engineering Software as a Service: An
Agile Approach Using Cloud Computing
NinJA
test
1
NinJA
NinJASon
test
1
test
2
※ 모듈은
상속되지 않는다.