Download pptx - Ruby on Rails – 1. Ruby

Transcript
Page 1: Ruby on Rails – 1. Ruby

Ruby on Rails – 1. RubyAON 의 공부하면서 만드는 세미나 1 탄

Page 2: Ruby on Rails – 1. Ruby

Ruby 는 어떤 언어 인가요 ?

왼쪽의 사진에 있는 분이 만든 언어입니다 ( 그래서 가장 최신자료는 일본어 ㅡㅡ )

Perl + Smalltalk + Ada + Eiffel + Lisp => Ruby

Imperative, Functional, following OOP

Yukihiro Matsumoto

Page 3: Ruby on Rails – 1. Ruby

Ruby 는 어떤 언어 인가요 ?

Ruby = an interpreted scripting language for quick and easy object-oriented programming!

Page 4: Ruby on Rails – 1. Ruby

Ruby 는 어떤 언어 인가요 ?

Ruby = an interpreted scripting language for quick and easy object-oriented programming!

- OS call 을 직접적으로 할 수 있다 - 문자열 연산이나 정규표현식에 큰 장점 - 개발하는 동안 즉각적인 피드백을 받을 수 있다

Page 5: Ruby on Rails – 1. Ruby

Ruby 는 어떤 언어 인가요 ?

Ruby = an interpreted scripting language for quick and easy object-oriented programming!

- 변수 선언이 필요 없고 타입 정할 필요도 ㄴㄴ - 문법이 단순단순 - 메모리 관리가 자동

Page 6: Ruby on Rails – 1. Ruby

Ruby 는 어떤 언어 인가요 ?

Ruby = an interpreted scripting language for quick and easy object-oriented programming!

- 모든 것이 객체객체해 (class, method, inheritance)

- module 사용 - singleton method

Page 7: Ruby on Rails – 1. Ruby

Ruby 는 어떤 언어 인가요 ?

Ruby = an interpreted scripting language for quick and easy object-oriented programming!

- 기타… - 예외처리가 편리함 - 숫자 담을 수 있는 범위가 존나 큼 !(40! 도 담을 수 있을 정도 ?)

- 쓰레드처리가 편리함

Page 8: Ruby on Rails – 1. Ruby

이제부터 본격적으로 시작 !

Page 9: Ruby on Rails – 1. Ruby

Ruby 를 사용하는 방법대화형 interpreter 를 이용하면 코드에 대한 결과를 바로 볼 수 있다 아래와 같이 shell 에 irb 를 입력하면 실행된다 .(irb = interactive ruby)

Page 10: Ruby on Rails – 1. Ruby

Ruby 를 사용하는 방법

파일명 .rb 에 스크립트를 작성해서 사용할 수도 있다 .

스크립트를 작성한 후에 $ ruby 파일명 .rb 로 스크립트를 실행할 수 있다 .

파일 가장 윗줄에 #! /usr/bin/env ruby 를 추가하면 ./ 파일명 .rb 로 스크립트를 실행할 수 있다 .

( 물론 그 전에 chmod +x 파일명 .rb 해야 되는건 알고 계시죠 ? ㅎㅎㅎ )

Page 11: Ruby on Rails – 1. Ruby

Ruby 를 사용하는 방법

Page 12: Ruby on Rails – 1. Ruby

Ruby 를 사용하는 방법

Page 13: Ruby on Rails – 1. Ruby

자 이제 진짜 시작 !!

참고로 puts 는 java 에서의 println 과 동일합니다 print 는 java 에서의 print 와 동일합니다 # 는 주석입니다

Page 14: Ruby on Rails – 1. Ruby

Ruby 의 숫자

Page 15: Ruby on Rails – 1. Ruby

Ruby 의 숫자 다른 언어에서의 Integer 범위 내 숫자 : Fixnum

다른 언어에서의 Integer 범위 외 숫자 : Bignum

1234 => Fixnum

123412341234123412341234123412341234 => Bignum

23.5432 => Float

12_23 => Fixnum ( 숫자 사이의 underscore 는 무시 )

Page 16: Ruby on Rails – 1. Ruby

Ruby 의 숫자 Math module 의 대표적인 method 들 - cos(x), sin(x) : 삼각함수 - log(x), exp(x) : 로그함수 , 지수함수 - sqrt(x) : 제곱근 함수 - 참고로 abs 는 없어요

Page 17: Ruby on Rails – 1. Ruby

Ruby 의 String

큰 따옴표와 작은 따옴표의 차이=> Escape 문자를 인식하냐 못하냐

문자열을 + 로 합치고 * 로 늘린다 !

Ruby 는 문자를 숫자로 인식하여ASCII 코드값을 내놓는다

Page 18: Ruby on Rails – 1. Ruby

Ruby 의 String

Substring 을 얻는 방식[ 시작점 , 길이 ], .. : 끝을 포함 , … : 끝을 포함하지 않음

String 의 equality

참고 ) “” 안에 #{ 코드 } 를 넣으면 코드의 결과가String 에 삽입된다 .

Page 19: Ruby on Rails – 1. Ruby

Ruby 의 String String 관련된 method 들 - to_c, to_i, to_f, to_r : string 에서 각각 복소수 , 정수 , 소수 , 분수로 형변환 => string.to_c 와 같이 씀 - length : string 의 길이 - split(pattern) : parameter 로 들어온 문자 혹은 패턴을 기준으로 string 을 나눔 - strip : 문자열 앞뒤로 whitespace 를 제거함 - reverse : string 을 뒤집음 - replace : 문자열을 다른 문자열로 대체함 - 여타 다른 method 들은 http://ruby-doc.org/core-2.0/String.html에서 직접 찾아보는 걸로

Page 20: Ruby on Rails – 1. Ruby

Array, Hash

Page 21: Ruby on Rails – 1. Ruby

Control Structure - if

if bool_expression1

#your code here

elsif bool_expression2 or your code if bool_expression

#your code here

else

#your code here

end

Page 22: Ruby on Rails – 1. Ruby

Control Structure - case

case x

when case1

#your code here

when case2

#your code here

end

Page 23: Ruby on Rails – 1. Ruby

Control Structure - while

while bool_expression

expression

end

your code while bool_expression

Page 24: Ruby on Rails – 1. Ruby

Control Structure - for

for element in collection

#your code here

end

Page 25: Ruby on Rails – 1. Ruby

Iteration string 을 위한 iterator

=> each_byte : string 의 각 문자에 대한 iterator

=> each_line : strin 의 각 줄에 대한 iterator

Array, Hash 등은 each, each_key, each_value 등을 활용하면 된다

yield 와 retry 를 이용하여 특정 code 를 반복실행할 수 있다 .

Page 26: Ruby on Rails – 1. Ruby

Block, Procs, Lambda Block

{} 내에 있는 코드

Procs

Function object

lambda {block} == Proc.new {block}

Page 27: Ruby on Rails – 1. Ruby

Function Definition

def foo(param)

# your code here

end

Page 28: Ruby on Rails – 1. Ruby

Class Definition class class_name

function1

function2

function3

end

Page 29: Ruby on Rails – 1. Ruby

Class Definition class Person

end

Page 30: Ruby on Rails – 1. Ruby

Class Definition class Person

def initialize(name)

@name = name

end

end

=> arteta = Person.new(“Mikel Arteta”)

Page 31: Ruby on Rails – 1. Ruby

Class Definition class Person

@@count = 0 # class variable( 다른 언어에서의 static 과 같음 )

def initialize(name)

@name = name

@@count += 1

end

def count

@@count

end

end

Page 32: Ruby on Rails – 1. Ruby

Class Definition class Car

$my =“a”

end

puts $my

=> global variable 을 위와 같이 class 내부에서 정의할 수 있음

Page 33: Ruby on Rails – 1. Ruby

Reader and writer class person

def initialize(name)

@name = name

end

def read_name

@name

end

def write_name(name)

@name = name

end

end

Page 34: Ruby on Rails – 1. Ruby

Reader and writer class person

def initialize(name)

@name = name

end

attr_reader :name

attr_writer :name

end

Page 35: Ruby on Rails – 1. Ruby

public private protected

Page 36: Ruby on Rails – 1. Ruby

Inheritance class subclass_name < class_name

function1

function2

function3

end

Page 37: Ruby on Rails – 1. Ruby

Module (= constant + functions) module Circle

PI = 3.14

def Circle.area(radius)

PI* radius ** 2

end

def Circle.circumference(radius)

2* PI * radius

end

end

Page 38: Ruby on Rails – 1. Ruby

Module Using constant

=> Circle::PI

Using function

=> Circle.area(4)

Using module not present in interpreter

=> require ‘date’

puts Date.today

Page 39: Ruby on Rails – 1. Ruby

Module in Class class Angle

include Math => instance level

attr_accessor :radians

def initialize(radians)

@radians = radians

end

def cosine

cos(@radians)

end

end

Page 40: Ruby on Rails – 1. Ruby

Module in Class module Simple

def say

puts “I’m simple”

end

end

Class SimpleMan

extend Simple => class level

end

SimpleMan.say

Page 41: Ruby on Rails – 1. Ruby

Exception Handling raise “message”

=> raise method 의 default exception 인 RunTimeError exception 을 message 와 함께 띄움

raise exception, “message”

=> 주어진 exception 과 message 를 함께 띄움

Page 42: Ruby on Rails – 1. Ruby

Exception Handling 다른 언어에서의 try catch 가 ruby 에서는 begin rescue 이다 .

def foo

begin

raise “something”

rescue

#begin 내에서 raise 가 실행되면 여기로 이동한다 .

end

end

Page 43: Ruby on Rails – 1. Ruby

세미나는 여기까지입니다 앞으로 이 세미나 내용을 숙지하고도 모르는 내용이 생긴다면 날카로운 통찰력과 매서운 구글링으로 위기를 헤쳐나가시길 바랍니다

Page 44: Ruby on Rails – 1. Ruby

다음 세미나 예고 다음주 이 시간 ! 추석을 끝내고 돌아오면 !

이제 rails 를 공부해본다

Page 45: Ruby on Rails – 1. Ruby

Ruby 후기 여기 세미나 내용을 공부하는데 걸리는 시간 : 최대 3 시간 ( 왜냐면 발표자가 이거 공부하는데 3 시간 걸렸기 때문 )

Python 이랑 다소 흡사하다는 느낌을 받음 => Python 을 잘 아는 우리 스팍스 회원들은 까다롭지 않게 공부할 수 있을 것이라고 믿음 !!

Page 46: Ruby on Rails – 1. Ruby

질문 받겠습니다

Page 47: Ruby on Rails – 1. Ruby

오타나 부족한 부분 있으면 [email protected]으로 알려주세요 ~