Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Ruby on Rails – 1. Ruby AON의 공부하면서 만드는 세미나 1탄 Ruby는 어떤 언어 인가요? 왼쪽의 사진에 있는 분이 만든 언어입니다 (그래서 가장 최신자료는 일본어 ㅡㅡ) Perl + Smalltalk + Ada + Eiffel + Lisp => Ruby Imperative, Functional, following OOP Yukihiro Matsumoto Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! - OS call을 직접적으로 할 수 있다 - 문자열 연산이나 정규표현식에 큰 장점 - 개발하는 동안 즉각적인 피드백을 받을 수 있다 Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! - 변수 선언이 필요 없고 타입 정할 필요도 ㄴㄴ - 문법이 단순단순 - 메모리 관리가 자동 Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! - 모든 것이 객체객체해(class, method, inheritance) - module 사용 - singleton method Ruby는 어떤 언어 인가요? Ruby = an interpreted scripting language for quick and easy object-oriented programming! - 기타… - 예외처리가 편리함 - 숫자 담을 수 있는 범위가 존나 큼!(40!도 담을 수 있을 정도?) - 쓰레드처리가 편리함 이제부터 본격적으로 시작! Ruby를 사용하는 방법 대화형 interpreter를 이용하면 코드에 대한 결과를 바로 볼 수 있다 아래와 같이 shell에 irb를 입력하면 실행된다.(irb = interactive ruby) Ruby를 사용하는 방법 파일명.rb에 스크립트를 작성해서 사용할 수도 있다. 스크립트를 작성한 후에 $ ruby 파일명.rb 로 스크립트를 실행할 수 있다. 파일 가장 윗줄에 #! /usr/bin/env ruby를 추가하면 ./파일명.rb로 스크립트를 실행할 수 있다. (물론 그 전에 chmod +x 파일명.rb 해야 되는건 알고 계시죠? ㅎㅎㅎ) Ruby를 사용하는 방법 Ruby를 사용하는 방법 자 이제 진짜 시작!! 참고로 puts는 java에서의 println과 동일합니다 print는 java에서의 print와 동일합니다 #는 주석입니다 Ruby의 숫자 Ruby의 숫자 다른 언어에서의 Integer 범위 내 숫자 : Fixnum 다른 언어에서의 Integer 범위 외 숫자 : Bignum 1234 => Fixnum 123412341234123412341234123412341234 => Bignum 23.5432 => Float 12_23 => Fixnum (숫자 사이의 underscore는 무시) Ruby의 숫자 Math module의 대표적인 method들 - cos(x), sin(x) : 삼각함수 - log(x), exp(x) : 로그함수, 지수함수 - sqrt(x) : 제곱근 함수 - 참고로 abs는 없어요 Ruby의 String 큰 따옴표와 작은 따옴표의 차이 => Escape 문자를 인식하냐 못하냐 문자열을 +로 합치고 *로 늘린다! Ruby는 문자를 숫자로 인식하여 ASCII 코드값을 내놓는다 Ruby의 String Substring을 얻는 방식 [시작점, 길이], .. : 끝을 포함, … : 끝을 포함하지 않음 String의 equality 참고) “”안에 #{코드}를 넣으면 코드의 결과가 String에 삽입된다. 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에서 직접 찾아보는 걸로 Array, Hash Control Structure - if if bool_expression1 #your code here elsif bool_expression2 #your code here else #your code here end or your code if bool_expression Control Structure - case case x when case1 #your code here when case2 #your code here … end Control Structure - while while bool_expression expression end your code while bool_expression Control Structure - for for element in collection #your code here end Iteration string을 위한 iterator => each_byte : string의 각 문자에 대한 iterator => each_line : strin의 각 줄에 대한 iterator Array, Hash 등은 each, each_key, each_value등을 활용하면 된다 yield와 retry를 이용하여 특정 code를 반복실행할 수 있다. Block, Procs, Lambda Block {} 내에 있는 코드 Procs Function object lambda {block} == Proc.new {block} Function Definition def foo(param) # your code here end Class Definition class class_name function1 function2 function3 end Class Definition class Person end Class Definition class Person def initialize(name) @name = name end end => arteta = Person.new(“Mikel Arteta”) Class Definition class Person @@count = 0 # class variable(다른 언어에서의 static과 같음) def initialize(name) @name = name @@count += 1 end def count @@count end end Class Definition class Car $my =“a” end puts $my => global variable을 위와 같이 class 내부에서 정의할 수 있음 Reader and writer class person def initialize(name) @name = name end def read_name @name end def write_name(name) @name = name end end Reader and writer class person def initialize(name) @name = name end attr_reader :name attr_writer :name end public private protected Inheritance class subclass_name < class_name function1 function2 function3 end 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 Module Using constant => Circle::PI Using function => Circle.area(4) Using module not present in interpreter => require ‘date’ puts Date.today Module in Class class Angle include Math => instance level attr_accessor :radians def initialize(radians) @radians = radians end def cosine cos(@radians) end end Module in Class module Simple def say puts “I’m simple” end end Class SimpleMan extend Simple => class level end SimpleMan.say Exception Handling raise “message” => raise method의 default exception인 RunTimeError exception을 message와 함께 띄움 raise exception, “message” => 주어진 exception과 message를 함께 띄움 Exception Handling 다른 언어에서의 try catch가 ruby에서는 begin rescue이다. def foo begin raise “something” rescue #begin 내에서 raise가 실행되면 여기로 이동한다. end end 세미나는 여기까지입니다 앞으로 이 세미나 내용을 숙지하고도 모르는 내용이 생긴다면 날카로운 통찰력과 매서운 구글링으로 위기를 헤쳐나가시길 바랍니다 다음 세미나 예고 다음주 이 시간! 추석을 끝내고 돌아오면! 이제 rails를 공부해본다 Ruby 후기 여기 세미나 내용을 공부하는데 걸리는 시간 : 최대 3시간 (왜냐면 발표자가 이거 공부하는데 3시간 걸렸기 때문) Python이랑 다소 흡사하다는 느낌을 받음 => Python을 잘 아는 우리 스팍스 회원들은 까다롭지 않게 공부할 수 있을 것이라고 믿음!! 질문 받겠습니다 오타나 부족한 부분 있으면 [email protected]으로 알려주세요~