ruby on rails – 1. ruby
Post on 02-Jan-2016
113 Views
Preview:
DESCRIPTION
TRANSCRIPT
Ruby on Rails – 1. RubyAON 의 공부하면서 만드는 세미나 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 or your code if bool_expression
#your code here
else
#your code here
end
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 을 잘 아는 우리 스팍스 회원들은 까다롭지 않게 공부할 수 있을 것이라고 믿음 !!
질문 받겠습니다
top related