ruby study 3

프로그래밍/Ruby 2009. 11. 9. 09:55

Access Control

 

Public methods : 어느곳에서든 호출이 가능하다.(, initialize 메소드 제외)

Protected methods : 상속받은 객체에서만 호출이 가능하다.

Private methods : 해당 메소드가 선언된 객체에서만 호출이 가능하다.

 

Specifying Access Control

 

class MyClass

           def method1

           end

          

           protected # protected 키워드가 선언된 하위의 메소드는 protected 로 설정된다.

           def method2

           end

          

           private # private 키워드가 선언된 하위의 메소드는 protected 로 설정된다.

           def method3

           end

          

           public # public 키워드가 선언된 하위의 메소드는 protected 로 설정된다.

           def method4

           end

end

 

class MyClass

           def method1

           end

          

           def method2

           end

          

           def method3

           end

          

           def method4

           end

          

           public :method1, :method4

           protected :method2

           private :method3

end

 

위와 같이 접근제어함수(public, protected, private) 에 설정도 가능하다.

 

샘플>

class Accounts

 

  private

 

    def debit(account, amount)

      account.balance -= amount

    end

    def credit(account, amount)

      account.balance += amount

    end

 

  public

 

    #...

    def transferToSavings(amount)

      debit(@checking, amount)

      credit(@savings, amount)

    end

    #...

end

 

class Account

  attr_reader :balance       # accessor method 'balance'

 

  protected :balance         # and make it protected

 

  def greaterBalanceThan(other)

    return @balance > other.balance

  end

end

 

Variables

 

person = "Tim"

=> "Tim" 을 값으로 갖는 String 객체를 생성한뒤 해당 객체의 참조값을 person 에 넘겨준다.

person.object_id

=> 22918640

person.class

=> String

person

=> Tim

 

person1 = "Tim"

person2 = person1 

=> person1 이 참조하고 있는 String 객체의 주소를 person2 에 설정한다.

person1[0] = 'J' 

person1

=>"Jim" 

person2

=>"Jim" 

 

person1 = "Tim"

person2 = person1.dup

=> person1 참조하고 있는 String 객체의 값을 person2 에 복사한다.

person1[0] = 'J' 

person1

=>"Tim" 

person2

=>"Jim"

 

person1 = "Tim"

person2 = person1

person1.freeze

=> person1 이 참조하고 있는 String 객체의 값을 변경하지 못하도록 한다.

person2[0] = 'J' 

=> error

 

Containers

 

Arrays

 

a = [3.14159, "pie", 99]

a.class => Array

a.length => 3

a[0] => 3.14159

a[1] => "pie"

a[2] => 99

a[3] => nil

b = Array.new

b.class => Array

b.length => 0

b[0] = "second"

b[1] = "array"

b => ["second", "array"]

 

a = [1, 3, 5, 7, 9]

a[-1] => 9

a[-2] => 7

a[-99] => nil

 

인덱스를 음수로 정의하면 -1 인덱스는 맨 마지막 값을 가리킨다.

 

a = [ 1, 3, 5, 7, 9 ] 

a[1, 3] => [3, 5, 7] 

a[3, 1] => [7] 

a[-3, 2] => [5, 7] 

 

[start, count] start 는 시작 인덱스 값을 나타내며 count 는 시작 인덱스 값부터 그 이후의 원소의 갯수를 타나낸다.

 

a = [1, 3, 5, 7, 9]

a[1..3] => [3, 5, 7]

a[1...3] => [3, 5] # ... 은 마지막 값을 제외하게 된다.

a[3..3] => [7]

a[-3..-1] => [5, 7, 9]

 

위와 같이 인덱스 범위를 설정할 수 있다.

 

a = [ 1, 3, 5, 7, 9 ] => [1, 3, 5, 7, 9]

a[1] = 'bat' => [1, "bat", 5, 7, 9]

a[-3] = 'cat' => [1, "bat", "cat", 7, 9]

a[3] = [ 9, 8 ] => [1, "bat", "cat", [9, 8], 9] # 인덱스에 배열도 할당이 가능하다.

a[6] = 99 => [1, "bat", "cat", [9, 8], 9, nil, 99] # a[5] 의 값은 할당되지 않았기 때문에 nil 이 할당된다.

 

a = [ 1, 3, 5, 7, 9 ] => [1, 3, 5, 7, 9]

a[2, 2] = 'cat' => [1, 3, "cat", 9]

a[2, 0] = 'dog' => [1, 3, "dog", "cat", 9]

a[1, 1] = [ 9, 8, 7 ] => [1, 9, 8, 7, "dog", "cat", 9]

a[0..3] = [] => ["dog", "cat", 9]

a[5] = 99 => ["dog", "cat", 9, nil, nil, 99]

 

Hashes

 

Array 가 정수를 인덱스로 가지는 반면에 Hash 는 객체를 인덱스로 가질 수 있다

 

h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' } 

 

h.length => 3 

h['dog'] => "canine" 

h['cow'] = 'bovine' 

h[12]    = 'dodecine' 

h['cat'] = 99 

h => {"cow"=>"bovine", "cat"=>99, 12=>"dodecine", "donkey"=>"asinine", "dog"=>"canine"} 

 

Implementing a SongList Container

 

SongList 클래스에서 구현할 메소드

append(aSong) # SongList Song 을 추가

deleteFirst() # 첫번째 Song을 제거

deleteLast() # 마지막 Song을 제거

[index] => sSong

 

class SongList

           def initialize

                     @songs = Array.new

           end

end

 

initialize 메소드에서는 간단하게 Song 을 담을 @songs 인스턴스 변수를 선언합니다.

 

def append(aSong)

           @songs.push(aSong)

           self

end

 

append 메소드에서는 인자로 넘겨진 Song @songs 배열에 추가한뒤 self 를 리턴합니다. self SongList 자기 자신을 의미합니다.

 

def deleteFirst

           @songs.shift

end

 

def deleteLast

           @songs.pop

end

 

Array shift 함수는 맨 첫 원소를 리턴후 배열에서 제거합니다.

Array pop 함수는 맨 마지막 원소를 리턴후 배열에서 제거합니다.

 

list = SongList.new

list.

  append(Song.new('title1', 'artist1', 1)).

  append(Song.new('title2', 'artist2', 2)).

  append(Song.new('title3', 'artist3', 3)).

  append(Song.new('title4', 'artist4', 4))

 

SongList append 함수에서 self SongList 를 리턴하기 때문에 append 메소드를 체인형태로 호출할 수 있습니다.

 

def [](key)

           if key.kind_of? (Integer)

                     @songs[key]

           end

end

 

kind_of? 함수는 (?까지 함수이름)

> key.kind_of?(Integer) # key Integer 형인지 아니면 Integer 의 하위 객체인지

 

list[0] => Song: title1--artist1 (1)

'프로그래밍 > Ruby' 카테고리의 다른 글

ruby study 2  (0) 2009.11.09
ruby study 1  (0) 2009.11.09
: