ruby study 1
프로그래밍/Ruby 2009. 11. 9. 09:53루비는 객체지향 언어이다.
song1 = Song.new("Ruby Tuesday")
song2 = Song.new("Enveloped in Python")
특징
1. 모든 객체는 object id 를 가진다.
2. 모든 객체는 자신의 상태를 저장하는 instance 변수를 갖는다.
루비에서 메소드를 사용하는 예제
"gin joint".length ≫ 9
"Rick".index("c") ≫ 2
-1942.abs ≫ 1942
sam.play(aSong) ≫ "duh dum, da dum de dum ..."
메소드 호출 원리
객체에 메세지를 보내면 메소드가 호출된다. 메세지는 메소드의 이름, 파라미터 를 포함한다.
객체가 메세지를 받으면 Class 에서 해당 메세지에 맞는 메소드를 발견하면 객체는 메소드를 실행한다.
메소드 호출에서 자바코드와의 비교
number = Math.abs(number) // 자바
number = number.abs // 루비
루비 기본
def sayGoodnight(name)
result = "Goodnight, " + name
return result
end
# Time for bed...
puts sayGoodnight("John-Boy")
puts sayGoodnight("Mary-Ellen")
- 문장 끝에 세미콜론 ; 을 붙일 필요가 없으며 개개의 문장은 분리된 행에 기술한다.
- 주석은 # 문자로 시작된다.
- 메소드는 def 키워드로 시작한다. def [메소드 이름]([메소드 인자])
- 메소드의 본문을 구별하기 위한 구분자( 예> { } ) 를 사용하지 않는다.
- 메소드의 마지막은 end 키워드로 끝낸다.
- 변수를 정의하지 않아도 된다.
- puts 메소드는 인자를 console 로 출력한다.
puts sayGoodnight("John-Boy") 은 아래처럼 호출할 수도 있다. 하지만 괄호를 사용하여 인자를 구분해주는게 좋다.
==========================================================
puts sayGoodnight "John-Boy"
puts sayGoodnight("John-Boy")
puts(sayGoodnight "John-Boy")
puts(sayGoodnight("John-Boy"))
- String Literal 내에서는 #{ expression } 을 사용할 수 있다.
result = "Goodnight, " + name => result = "Goodnight, ${name}"
루비에서 변수명
- 지역변수, 메소드 인자, 메소드 이름은 첫번째 문자를 소문자나 _(underscore) 로 시작한다.
- Global 변수는 $ 로 시작한다.
- instance 변수는 @ 로 시작한다.
- Class 변수는 @@ 로 시작한다.
- Class 이름은 첫번째 문자가 대문자로 시작한다.
Example variable and class names
Variables
Constants and
Local
Global
Instance
Class
Class Names
name
$debug
@name
@@total
PI
fishAndChips
$CUSTOMER
@point_1
@@symtab
FeetPerMile
x_axis
$_
@X
@@N
String
thx1138
$plan9
@_
@@x_pos
MyClass
_26
$Global
@plan9
@@SINGLE
Jazz_Song
'프로그래밍 > Ruby' 카테고리의 다른 글
ruby study 3 (0) | 2009.11.09 |
---|---|
ruby study 2 (0) | 2009.11.09 |