How to use the Ruby programing language

67
Kookmin University Graduate School of Busuness IT e-Government System Development 석사 1학기 안 재열

Transcript of How to use the Ruby programing language

Page 1: How to use the Ruby programing language

Kookmin UniversityGraduate School of Busuness IT

e-Government System Development

석사 1학기 안 재열

Page 2: How to use the Ruby programing language

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

Page 3: How to use the Ruby programing language

What is the Ruby?

Page 4: How to use the Ruby programing language

Who made the Ruby?

• 마츠모토 유키히로

• 프로그래머

• 마츠모토 유키히로 는 루비를 개발한 프로그래머이다.

일본 오사카 부 태생. 고등학교까지 독학으로 프로그

래밍을 익혔으며, 쓰쿠바 대학교 정보학부를 나와,

• 시마네대학 대학원에서 박사과정을 취득했다. 2006

년 현재, 시마네 현에서 오픈소스 관련 회사인 네트워

크 응용통신 연구소의 특별 연구원으로 재직하고 있

다. 마츠모토는 결혼하여 4명의 아이들이 있다.

• 출생: 1965년 4월 14일 (49세), 일본 오사카 부 오사카 시

• 학력: 쓰쿠바 대학

Page 5: How to use the Ruby programing language

Why made the Ruby?

• 마츠모토 유키히로 : 프로그램을 짜는 것이

쉬워즈는 것 뿐만 아니라,

• 프로그래머가 즐거워지도록 설계했습니다.

• 저는 많은 프로그래밍 언어를 알지만, 그 어느것에서도 만

족할 수 없었습니다. 제가 기대한 것 보다 보기 흉하거나,

거칠거나, 복잡하거나, 너무 간단했습니다.

• 그래서 스스로 만졸할만한 자신만의 언어를 만들고 싶었습

니다. 자신을 위한 언어라서 어디가 가려운 곳인지 잘 알고

있었습니다. 깜짝놀란 것은 이세상에는 저처럼 느끼는 프로

그래머가 수없이 많다는 것입니다.

• 루비를 개발하면서 프로그래밍을 더 빠르고 ‘쉽게’ 하는데

집중했습니다.

Page 6: How to use the Ruby programing language

codecademy

• http://www.codecademy.com/learn

Page 7: How to use the Ruby programing language

Cloud 9 (Saas)

• https://c9.io

• Ubuntu + Rails + Ruby + IDE_Tool +(Git Hub)

Page 8: How to use the Ruby programing language

Reference

저자: 유키히로마츠모토Rubyists bible마틴파울러추천저자: 유키히로마츠모토 마틴파울러추천유키히로추천

실습위주 뼈대잡기, 훝기….

Page 9: How to use the Ruby programing language

Intro

Page 10: How to use the Ruby programing language

Everything is object in Ruby

• (※ 주석은 #으로 시작하고 =>는 명령어를 실행했을때 반환되는 값을 나타냅니다.)

1.class #=>Fixnum0.0.class #=>FloatTrue.class #=>TrueClassFalse.class #=>FalseClassNil.class #=>NilClassFalse.class #=>FalseClassNil.class #=>NilClass

1.class #=>Fixnum

Method (메소드)

Page 11: How to use the Ruby programing language

Method in Ruby

• Method form in ruby

def (parameter1, parameter2, parameter3…)

Doing Something

end

• Parentheses are usually optional in Ruby.

• 보통 parameter 혹은 리턴의 대상이 한 개일 때 생략한다.

end

Page 12: How to use the Ruby programing language

Method in Ruby

• Implicit Return

• Parentheses are usually optional in Ruby.

• 보통 parameter 혹은 리턴의 대상이 한 개일 때 생략한다.

Interpolation 보간법

Page 13: How to use the Ruby programing language

Interpolation

• Interpolation

• Interpolation allows Ruby code to appear within a string. The result of evaluating that code is inserted into the string:

• "1 + 2 = #{1 + 2}" #=> "1 + 2 = 3"

#{expression}

Page 14: How to use the Ruby programing language

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.

불완전한문장(이어짐)

완전한문장(종료)완전한문장(종료)

문장연결

Page 15: How to use the Ruby programing language

Interpolation

• Interpolation

• Interpolation allows Ruby code to appear within a string. The result of evaluating that code is inserted into the string:

• "1 + 2 = #{1 + 2}" #=> "1 + 2 = 3"

#{expression}

Page 16: How to use the Ruby programing language

Dynamic Typing

• Ruby is dynamically typed: the type of a variable is generally not inferable untilruntime. So s=5 can follow s=” foo” in the same block of code.

• Because variables do not have types.

Page 17: How to use the Ruby programing language

Dynamic Typing

• Ruby is dynamically typed: the type of a variable is generally not inferable untilruntime. So s=5 can follow s=” foo” in the same block of code.

• Because variables do not have types.

Page 18: How to use the Ruby programing language

Dynamic Typing

• Ruby is dynamically typed: the type of a variable is generally not inferable untilruntime. So s=5 can follow s=” foo” in the same block of code.

• Because variables do not have types.

Page 19: How to use the Ruby programing language

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

Page 20: How to use the Ruby programing language

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 humansto read or write, but that do not change the functionality or expressiveness of thelanguage. -Wikipidea

Page 21: How to use the Ruby programing language

Every Operation is a Method Call

• 객체가 갖고 있는 것

• 클래스 상속 구조

• 객체의 속성과 메소드

• 메소드에 대한 정보

리플렉션 (Reflection)

루비와 같은 동적 언어의 많은 장점 중 하나는 인트로스페션(introspection)이 가능하다는 점이다.

즉 프로그램 스스로 자기자신의 생긴 모양을 살펴 볼 수 있다는 의미.

Page 22: How to use the Ruby programing language

Every Operation is a Method Call

• 원하는 클래스의 객체 사용현황파악• (※Fixnum,Symbol,true,nill등 즉시 값을 갖는 객체는 사용불가)

• ObjectSpace.each_object(Some_class) {|x| p x}

리플렉션 (Reflection)

Page 23: How to use the Ruby programing language

Every Operation is a Method Call

• 인스턴스내의 메소드 확인

instance name.respond_to(“method name”)

리플렉션 (Reflection)

Page 24: How to use the Ruby programing language

Every Operation is a Method Call

• 객체(인스턴스)에 대해서 살펴보는 것은 리플렉션의 한 측면 일 뿐

• 전체 그림을 얻기 위해서는 클래스에 대해서도 알아야 한다.

리플렉션 (Reflection)

Page 25: How to use the Ruby programing language

Every Operation is a Method Call

• 객체(인스턴스)에 대해서 살펴보는 것은 리플렉션의 한 측면 일 뿐

• 전체 그림을 얻기 위해서는 클래스에 대해서도 알아야 한다.

리플렉션 (Reflection)

Page 26: How to use the Ruby programing language

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

Page 27: How to use the Ruby programing language

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!

Page 28: How to use the Ruby programing language

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)

…}

Page 29: How to use the Ruby programing language

Every Operation is a Method Call

Duck Typing ; ( Viewpoint, philosophy )

클래스 타입 비교 - JAVA, C#

Page 30: How to use the Ruby programing language

Every Operation is a Method Call

Duck Typing ; ( Viewpoint, philosophy )

객체 보유 함수(메소드) 기준 검사

Page 31: How to use the Ruby programing language

Every Operation is a Method Call

Duck Typing ; ( Viewpoint, philosophy )

자유방임주의스타일 (laissez-faire)

Page 32: How to use the Ruby programing language

Every Operation is a Method Call

• lets us define new code at runtime.

메타프로그래밍(metaprogramming)

Page 33: How to use the Ruby programing language

Every Operation is a Method Call

Page 34: How to use the Ruby programing language

Iterator (Do-While)

Begin

#doing Something.

End while (true) #While not false or not nil.

Page 35: How to use the Ruby programing language

Iterator (Do-While)

Begin

#doing Something.

End while (true) #While not false or not nil.

Page 36: How to use the Ruby programing language

Iterator (While)

while (true) do #While not false or not nil

#doing Something.

End

Page 37: How to use the Ruby programing language

Iterator (While)

while (true) do #While not false or not nil

#doing Something.

End

Page 38: How to use the Ruby programing language

Iterator (For)

for var in collection

#doing Something.

End

Page 39: How to use the Ruby programing language

Iterator (For)

for var in collection

#doing Something.

End

Page 40: How to use the Ruby programing language

Iterator (Use the method)

Page 41: How to use the Ruby programing language

Iterator (Each; Enumerable)

Collection.each do |var| doing something end

Collection.each { |var| doing something }

Hash, Array, Range 등 많은 클래스에 정의되어 있는 each!

Page 42: How to use the Ruby programing language

Blocks and Yield

Def call_backputs “Start of method”yieldyieldputs “End of method”

End

Result :Start of methodIn the blockIn the blockEnd of method

Yield : 넘겨주다, 양도하다인스턴스명.메소드명(argument) {|parameter| doing something.}

EndCall_block {puts “In the block”}

Def call_blockyield(“hello”, 99)

End

call_block {|str, num| …} blockblock

Page 43: How to use the Ruby programing language

Blocks and Yield

Page 44: How to use the Ruby programing language

Blocks and Yield

Yield : 넘겨주다, 양도하다인스턴스명.메소드명(argument) {|parameter| doing something.}

blockblock

Block을 통해 inner function 또는 inner method를 구현 할 수 있다.

Page 45: How to use the Ruby programing language

Blocks and Yield

인스턴스명.메소드명(argument) {|parameter| doing something.}

Page 46: How to use the Ruby programing language

Blocks and Yield

Yield : 넘겨주다, 양도하다

인스턴스명.메소드명(argument) {|parameter| doing something.}

Page 47: How to use the Ruby programing language

Blocks and Yield

Def each

for each element

yield(element)

end

end

※추측Each 반복자의 구성은 다음과 같을 것이다.

Page 48: How to use the Ruby programing language

Proc & Lambda : Savable Blocks!

Page 49: How to use the Ruby programing language

Proc & Lambda : Savable Blocks!

Proc Proc.new { puts "Hello!" }

Lambda lambda { puts "Hello!" }

Page 50: How to use the Ruby programing language

Proc & Lambda : Savable Blocks!

Proc Lambda

Checking Arguments X O

if you pass it the wrong number ofarguments

Ignoreandassign nil

throw an error

control back to the calling method X O

즉시종료 통제권반환

Page 51: How to use the Ruby programing language

closure

closure : 클로저(closure)는 내부함수가 외부함수의 맥락(context)에 접근할 수 있는 것을 가르킨다.

내부함수는 외부함수의 지역변수에 접근 할 수 있는데,

외부함수의 실행이 끝나서 외부함수가 소멸된 이후에도 내부함수가 외부함수의 변수에 접근 할 수 있다.

이러한 메커니즘을 클로저라고 한다.

123456

function factory_movie(title){return {

get_title : function (){return title;

실행결과Ghost in the shell -> Matrix -> 공각기동대 -> Matrix

Javascript

67891011121314151617181920

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());

Page 52: How to use the Ruby programing language

closure

closure : 클로저(closure)는 내부함수가 외부함수의 맥락(context)에 접근할 수 있는 것을 가르킨다.

내부함수는 외부함수의 지역변수에 접근 할 수 있는데,

외부함수의 실행이 끝나서 외부함수가 소멸된 이후에도 내부함수가 외부함수의 변수에 접근 할 수 있다.

이러한 메커니즘을 클로저라고 한다.

함수(메소드) Aint var1 1) Test = 함수 A

2) Test 실행

return 함수(메소드) B

함수(메소드) B

print var1

2) Test 실행

3) 결과?

Var1이 나오는가 안나오는가?

BlockProc

Lambda

Page 53: How to use the Ruby programing language

closure

Page 54: How to use the Ruby programing language

closure

def multiply(m) test = multiply(2) -> 외부함수 변수대입def multiply(m)n = mreturn lambda{|data|data.collect{|x| x*n}}

end

test = multiply(2)

puts test.call([1,2,3])

test = multiply(2) -> 외부함수 변수대입

def multiply(2)n = 2return 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)라고 한다.

Page 55: How to use the Ruby programing language

closure

Lambda 는 정의된 범위 밖에서 사용되고, 메서드 인수 n을가두므로(Close Over) 클로저(Closure)라고 한다.

Private 변수처럼 이용하는 모습- OOP에서 하나의 인스턴스와 유사하게 보인다.

Page 56: How to use the Ruby programing language

closure

Page 57: How to use the Ruby programing language

class

Page 58: How to use the Ruby programing language

class

생성자 (Constructor)

인스턴스 변수(instance variable)

인스턴스화 (Instantiating)

Page 59: How to use the Ruby programing language

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

Page 60: How to use the Ruby programing language

Inheritance

Page 61: How to use the Ruby programing language

Methods visibility

Page 62: How to use the Ruby programing language

Modules & Mix-in

기능 (Method) :날씨별 음악재생기능변수(Constant value) :

습도 80% = 80

속도

온도

1936년 부가티 타입 57SC아틀란틱

Alias = my car

Instance class

Instance

Page 63: How to use the Ruby programing language

Modules & Mix-in

Page 64: How to use the Ruby programing language

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: AnAgile Approach Using Cloud Computing

NinJA

test1

NinJA

NinJASontest1

test2

※ 모듈은상속되지 않는다.

Page 65: How to use the Ruby programing language

Modules & Mix-in

Page 66: How to use the Ruby programing language

Modules & Mix-in

Page 67: How to use the Ruby programing language

Thank you!