Ruby 언어 기본 문법
루비언어의 특성을 자바나 다른 언어에 비해서 다른 부분만 요약 정리
Class,Object
- 클래스 변수는 @@를 사용해서 정의 @@name = 'hello'
클래스 메서드는 클래스로만 호출 가능. object에서는 호출 불가
클래스 변수나 메서드에 대해서는 http://dimdim.tistory.com/entry/Ruby-%ED%81%B4%EB%9E%98%EC%8A%A4-%EA%B0%9D%EC%B2%B4-%EB%B3%80%EC%88%98 보고 다시 정리 필요
Object
- 생성 : New를 이용해서 class로 부터 생성 Class명.new 로 생성. 예 object=MyClass.new
- 객체 변수는 @를 사용해서 정의 예 @hello = hello
- Putter와 Setter
class Horse
def name # getter
@name
end
def name=( value ) # setter
@name = value
end
end
Module
- Module : 외부에서 import되는 라이브러리로, Object 처럼 new로 생성이 불가. require를 이용해서 불러옴. include를 이용해서 Statement를 통째로 넣을 수 있음
모듈 예)
#dics.rb
module Dice
# virtual roll of a pair of dice
def roll
p 'im in module'
end
end
#game.rb
require 'dice'
class Game
include Dice
end
g = Game.new
g.roll
==> im in module
변수
- 전역 변수는 $를 사용 $global=10
- Type은 define하지 않음 x=10, mystring="hello" 식으로 정의함
- 문자열은 ' 또는 " 양쪽 다 사용 가능함
숫자 타입
- 일반 연산자는 같음
- ** : 제곱
배열
- 배열 : [] 로 감쌈 - a = [1,2]. print a[0]
- 해쉬 : {} 로 감쌈 Key/value는 =>로 구별 지정 - h = {"name"=>"terry","address"=>"seoul"} , p h["terry"]
- 배열,해쉬 traverse :
a.each do |e|
p e
end
메서드 정의
- def hello
# logic
end
- 리턴 방식은 return 을 그냥 사용 또는 리턴 값을 return 없이 그냥 써도 됨
def f
10
end
f() #==> 10이 출력됨
- 인자가 있는 경우 def hello(name,age)
- 디폴트 값이 있는 경우 def hello(name="terry",age) 이경우 호출은 hello(40)
- Variable argument 를 넘길때는 *를 사용함 def sayhello(var,*vars)
Comment
- 주석은 #를 사용함
Ruby 언어만의 좀 특이한 특성
Block
- {} 로 둘러싸인 코드 블럭
- yield를 호출하면 코드 블럭으로 치환함 (일종의 include와 같은 효과)
예)
def func
p "hello"
yield
p "world"
yield
end
func { p "this is code block"}
실행 결과 =>
"hello"
"this is code block"
"world"
"this is code block"
=> "this is code block" # 이건 리턴 값
Procs
- 일종의 함수 포인트와 같은 개념
- name = Proc.new{ statement로 로직 정의}
name.call 하면 statement가 실행됨
Symbol
- :로 시작함
- 조금더 research 필요
Quick Reference는 http://www.tutorialspoint.com/ruby/를 참조하면 좋음
'프로그래밍 > Ruby' 카테고리의 다른 글
Ruby 개발환경 설정하기 (윈도우7에서) (1) | 2014.08.18 |
---|