Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Ruby on Rails – 1. Ruby Aon의 공부하면서 만드는 세미나 1탄."— Presentation transcript:

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

2 Ruby는 어떤 언어 인가요? Perl + Smalltalk + Ada + Eiffel + Lisp => Ruby
왼쪽의 사진에 있는 분이 만든 언어입니다 (그래서 가장 최신자료는 일본어 ㅡㅡ) Perl + Smalltalk + Ada + Eiffel + Lisp => Ruby Imperative, Functional, following OOP Yukihiro Matsumoto

3 Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming!

4 Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! - OS call을 직접적으로 할 수 있다 - 문자열 연산이나 정규표현식에 큰 장점 - 개발하는 동안 즉각적인 피드백을 받을 수 있다

5 Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! - 변수 선언이 필요 없고 타입 정할 필요도 ㄴㄴ - 문법이 단순단순 - 메모리 관리가 자동

6 Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! - 모든 것이 객체객체해(class, method, inheritance) - module 사용 - singleton method

7 Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! - 기타… - 예외처리가 편리함 - 숫자 담을 수 있는 범위가 존나 큼!(40!도 담을 수 있을 정도?) - 쓰레드처리가 편리함

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

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

10 Ruby를 사용하는 방법 파일명.rb에 스크립트를 작성해서 사용할 수도 있다.
파일 가장 윗줄에 #! /usr/bin/env ruby를 추가하면 ./파일명.rb로 스크립트를 실행할 수 있다. (물론 그 전에 chmod +x 파일명.rb 해야 되는건 알고 계시죠? ㅎㅎㅎ)

11 Ruby를 사용하는 방법

12 Ruby를 사용하는 방법

13 자 이제 진짜 시작!! 참고로 puts는 java에서의 println과 동일합니다
print는 java에서의 print와 동일합니다 #는 주석입니다

14 Ruby의 숫자

15 Ruby의 숫자 다른 언어에서의 Integer 범위 내 숫자 : Fixnum
다른 언어에서의 Integer 범위 외 숫자 : Bignum 1234 => Fixnum => Bignum => Float 12_23 => Fixnum (숫자 사이의 underscore는 무시)

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

17 Ruby의 String 큰 따옴표와 작은 따옴표의 차이 => Escape 문자를 인식하냐 못하냐
문자열을 +로 합치고 *로 늘린다! Ruby는 문자를 숫자로 인식하여 ASCII 코드값을 내놓는다

18 Ruby의 String Substring을 얻는 방식 [시작점, 길이], .. : 끝을 포함, … : 끝을 포함하지 않음
“123#{2+2}” => “1234” String의 equality 참고) “”안에 #{코드}를 넣으면 코드의 결과가 String에 삽입된다.

19 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들은 직접 찾아보는 걸로

20 Array, Hash

21 Control Structure - if if bool_expression1 #your code here
elsif bool_expression or your code if bool_expression else end

22 Control Structure - case case x when case1 #your code here when case2
end

23 Control Structure - while while bool_expression expression end
your code while bool_expression

24 Control Structure - for for element in collection #your code here end

25 Iteration string을 위한 iterator
=> each_byte : string의 각 문자에 대한 iterator => each_line : strin의 각 줄에 대한 iterator Array, Hash 등은 each, each_key, each_value등을 활용하면 된다 yield와 retry를 이용하여 특정 code를 반복실행할 수 있다. "abc".each_byte{|c| printf "<%c>", c}; print "\n“ "a\nb\nc\n".each_line{|l| print l} ruby> def repeat(num)     |   while num > 0     |     yield     |     num -= 1     |   end     | end    nil ruby> repeat(3) { puts "foo" } foo foo foo    nil ruby> def WHILE(cond)     |   return if not cond     |   yield     |   retry     | end    nil ruby> i=0; WHILE(i<3) { print i; i+=1 } 012   nil

26 Block, Procs, Lambda Block {} 내에 있는 코드 Procs Function object
lambda {block} == Proc.new {block} 5.times {puts "I'm a block!"} [1, 2, 3].each { |num| puts num } fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]# Add your code below!doubled_fibs = fibs.collect {|x| x*2} def block_test puts "We're in the method!" puts "Yielding to the block..." yield puts "We're back in the method!"endblock_test { puts ">>> We're in the block!" } def yield_name(name) puts "In the method! Let's yield." yield name puts "Block complete! Back in the method."endyield_name("Eric") { |name| puts "My name is #{name}." }# Now call the method with your name!yield_name("Jongwook Chae") { |name| puts "My name is #{name}."} multiples_of_3 = Proc.new do |n| n % 3 == 0end(1..100).to_a.select(&multiples_of_3) floats = [1.2, 3.45, 0.91, 7.727, 11.42, ]# Write your code below this line!round_down = Proc.new { |x| x.to_i }# Write your code above this line!ints = floats.collect(&round_down) hi = Proc.new {puts "Hello!"}hi.call def lambda_demo(a_lambda) puts "I'm the method!" a_lambda.callendlambda_demo(lambda { puts "I'm the lambda!" })

27 Function Definition def foo(param) # your code here end

28 Class Definition class class_name function1 function2 function3 end
class Song   def initialize(name, artist, duration)   end end class KaraokeSong < Song   def initialize(name, artist, duration, lyrics)     super(name, artist, duration)   end end class Song   def initialize(name, artist, duration)   end   def play   end end

29 Class Definition class Person end

30 Class Definition class Person def initialize(name) @name = name end
=> arteta = Person.new(“Mikel Arteta”)

31 Class Definition class Person
= 0 # class variable(다른 언어에서의 static과 같음) def initialize(name) @name = name += 1 end def count

32 Class Definition class Car $my =“a” end puts $my
=> global variable을 위와 같이 class 내부에서 정의할 수 있음

33 Reader and writer class person def initialize(name) @name = name end
def read_name @name def write_name(name)

34 Reader and writer class person def initialize(name) @name = name end
attr_reader :name attr_writer :name

35 public private protected
class MyClass       def method1    # default is 'public'         #...       end   protected          # subsequent methods will be 'protected'       def method2    # will be 'protected'         #...       end   private            # subsequent methods will be 'private'       def method3    # will be 'private'         #...       end   public             # subsequent methods will be 'public'       def method4    # and this will be 'public'         #...       end end Alternatively, you can set access levels of named methods by listing them as arguments to the access control functions.   def method1   end   # ... and so on   public    :method1, :method4   protected :method2   private   :method3 end

36 Inheritance class subclass_name < class_name function1 function2
end class KaraokeSong < Song   def initialize(name, artist, duration, lyrics)     super(name, artist, duration)   end end

37 Module (= constant + functions)
module Circle PI = 3.14 def Circle.area(radius) PI* radius ** 2 end def Circle.circumference(radius) 2* PI * radius

38 Module Using constant => Circle::PI Using function
=> Circle.area(4) Using module not present in interpreter => require ‘date’ puts Date.today

39 Module in Class class Angle include Math => instance level
attr_accessor :radians def initialize(radians) @radians = radians end def cosine

40 Module in Class module Simple def say puts “I’m simple” end
Class SimpleMan extend Simple => class level SimpleMan.say

41 Exception Handling raise “message”
=> raise method의 default exception인 RunTimeError exception을 message와 함께 띄움 raise exception, “message” => 주어진 exception과 message를 함께 띄움

42 Exception Handling 다른 언어에서의 try catch가 ruby에서는 begin rescue이다. def foo
raise “something” rescue #begin 내에서 raise가 실행되면 여기로 이동한다. end

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

44 다음 세미나 예고 다음주 이 시간! 추석을 끝내고 돌아오면! 이제 rails를 공부해본다

45 Ruby 후기 여기 세미나 내용을 공부하는데 걸리는 시간 : 최대 3시간
(왜냐면 발표자가 이거 공부하는데 3시간 걸렸기 때문) Python이랑 다소 흡사하다는 느낌을 받음 => Python을 잘 아는 우리 스팍스 회원들은 까다롭지 않게 공부할 수 있을 것이라고 믿음!!

46 질문 받겠습니다

47 오타나 부족한 부분 있으면 jwchae8@gmail.com으로 알려주세요~


Download ppt "Ruby on Rails – 1. Ruby Aon의 공부하면서 만드는 세미나 1탄."

Similar presentations


Ads by Google