2. 기본문법2(class, object and variables)

IT(Old)/RubyOnRails 2008. 1. 15. 14:23

1. Class, Object and Variables(루비)

class Song
  def initialize(name, artist, duration)
     @name = name
     @artist = artist
     @duration = duration
  end
end

initialize는 Ruby에서 특별한 method다. Song.new로 객체를 생성할때 new뒤에 붙는 파라미터들은
initialize메소드로 들어가게된다.

aSong = Song.new{"Bicylops", "Fleck", 260}

예제)
class Song
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
 
  def to_s
    "Song:
#{@name}--#{@artist} (#{@duration})"
  end
end

aSong = Song.new("Bicylops", "Fleck", 260)
aSong.to_s
>> Song: Bicylops--Fleck (260)



2. Inheritance and Messages

class KaraokeSong < Song
  def initialize(name, artist, duration, lyrics)
     super(name, artist, duration)
     @lyrics = lyrics
  end
end

"< Song" 은 KaraokeSong이 Song의 sub클래스임을 의미한다.
다시한번

class Song
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
 
  def to_s
    "Song:
#{@name}--#{@artist} (#{@duration})"
  end
end

class KaraokeSong < Song
  def initialize(name, artist, duration, lyrics)
    super(name, artist, duration)
    @lyrics = lyrics
  end
 
  def to_s
    "Song:
#{@name}--#{@artist} (#{@duration}) #{@lyrics}"
  end
end

aSong = Song.new("Bicylops", "Fleck", 260)
puts aSong.to_s

bSong = KaraokeSong.new("My Way", "Sinatra", 225, "And new, the...")
puts bSong.to_s

>>
Song: Bicylops--Fleck (260)
Song: My Way--Sinatra (225) And new, the...

이것을 다시 Ruby 문법으로 간단하게 바꿔보자

KaraokeSong의 to_s를
"Song: #{@name}--#{@artist} (#{@duration}) #{@lyrics}"  => super + " #{@lyrics}"
로 바꾸면 더욱 간단해 진다.

3. Inheritance and Mixins

ruby는 단일상속만 지원하지만 많은수의 mixins기능을 포함할 수 잇따
(몬말인지는 나중에 설명한다... ㅡ.ㅡ)

4. Object and Attributes

앞서 작성한 song객체의 state는 private상태이다. 다른 곳에서 부를수가 없다는 말이겠지

class Song
 
  attr_reader :name, :artist, :duration
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
 
  def name
    @name
  end
   
  def artist
    @artist
  end
   
  def duration
    @duration
  end
end

aSong = Song.new("Bicylops", "Fleck", 260)
puts aSong.artist
puts aSong.name
puts aSong.duration


로칼변수를 write하기 위해서는

  def duration=(newDuration)
    @duration = newDuration
  end
또는
  attr_writer :duration

을 사용해라(주의 def duration=(newDuration) 에 스페이스는 없어야된다.)

5. Virtual Attributes

class Song
  def durationInMinutes
     @duration/60.0
  end
end

aSong.durationInMinues

처럼 가상의 변수를 만들어 사용할 수 잇따.

6. Class Variables and Class Methods

- class variables

class Song
  @@plays = 0
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
    @plays    = 0
  end
  def play
    @plays += 1
    @@plays += 1
    "This  song: #@plays plays. Total #@@plays plays."
  end
end


s1 = Song.new("Song1", "Artist1", 234)  # test songs..
s2 = Song.new("Song2", "Artist2", 345)
s1.play » "This  song: 1 plays. Total 1 plays."
s2.play » "This  song: 1 plays. Total 2 plays."
s1.play » "This  song: 2 plays. Total 3 plays."
s1.play » "This  song: 3 plays. Total 4 plays."


- class methods

class SongList
  MaxTime = 5*60           #  5 minutes
  def SongList.isTooLong(aSong)
    return aSong.duration > MaxTime
  end
end
song1 = Song.new("Bicylops", "Fleck", 260)
SongList.isTooLong(song1) » false
song2 = Song.new("The Calling", "Santana", 468)
SongList.isTooLong(song2) » true


7. Singletons and Other Constructors

singletons를 사용하기 위해서는 new의 사용을 막고,
create같은 method를 사용해라.

class Logger
  private_class_method :new
  @@logger = nil
  def Logger.create
    @@logger = new unless @@logger
    @@logger
  end
end

puts Logger.create.id
puts Logger.create.id
>>
22918100
22918100

class Shape
  def Shape.triangle(sideLength)
    Shape.new(3, sideLength*3)
  end
  def Shape.square(sideLength)
    Shape.new(4, sideLength*4)
  end
end


8. Access Control

- public methods : 누구나 호출가능
- protected methods : 상속받은 sub class만 호출가능
- private methods : 외부에서는 호출할 수 없음

하지만 Ruby는 다른 OO언어들과는 다르다. Access control은 프로그램이 실행될 때 동적으로 결정된다.
당신은 제한된 mothod를 실행하기 시도할때만 당신은 이 규칙을 위반할 수 있다.

Specifying Access Control
public, protected, private를 사용하여 class나 module정의할때 access level을 정의할 수 있다.

class MyClass

      def method1    # default is 'public'
        #...
      end

  protected          # subsequent methods will be 'protected'

      def method2    # will be 'protected'
        #...
      end

  private            # subsequent methods will be 'private'

      def method3    # will be 'private'
        #...
      end

  public             # subsequent methods will be 'public'

      def method4    # and this will be 'public'
        #...
      end
end


다른 방법으로는

class MyClass

  def method1
  end

  # ... and so on

  public    :method1, :method4
  protected :method2
  private   :method3
end


클래스의 initialize method는 자동으로 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


9. Variables

person = "Tim"
puts person.id
puts person.type
puts person
>>
22918640
String
Tim



person1 = "Tim"
person2 = person1
person1[0] = 'J'
puts person1
puts person2
>>
Jim
Jim

person1 = "Tim"
person2 = person1.dup
person1[0] = 'J'
puts person1
puts person2
>>
Jim
Tim

person1 = "Tim"
person2 = person1
person1.freeze    # prevent modifications to the object
person2[0] = "j"
>>
Logger.rb:4:in `[]=': can't modify frozen string (TypeError)
















1. 기본문법1 (Ruby.new)

IT(Old)/RubyOnRails 2008. 1. 15. 11:15

1 .객체 생성
생성자라는 것에 의해 객체가 생성됨. new가 standard constructor

song1 = Song.new("Ruby Tuesday")
song2 = Song.new("Enveloped in Python")
# and so on

2. method call

"gin joint".length     >> 9
"Rick".index("c")    >> 2
-1942.abs              >> 1942
sam.play(aSong)    >> "duh dum, da dum de dum ..."

3. A method that return a string

def sayGoodnight(name)
  result  = "Goodnight, " + name
  return result
end

# Time for bed ...
puts sayGoodnight("John-Boy")
puts sayGoodnight("Mary-Ellen")

>> Goodnight, John-Boy
>> Goodnight, Mary-Ellen

puts sayGoodnight "John-Boy1"
puts sayGoodnight("John-Boy2")
puts (sayGoodnight "John-Boy3")
puts (sayGoodnight ("John-Boy4"))

>> Goodnight, John-Boy1
>> Goodnight, John-Boy2
>> Goodnight, John-Boy3
>> Goodnight, John-Boy4

4. double-quoted strings

- ""안에서 개행문자는 \n을 사용한다.
puts "And Goodnight, \nGrandma"

>> And Goodnight,
>> Grandma

- ""안에서 변수는 #{expression} 을사용한다
def sayGoodnight(name)
  result = "Goodnight, #{name}:
  return result
end


5. 명명규칙

Local variables, method paramethers 그리고 method names은 소문자로 시작되어야 한다.
class, module , constants는 대문자로 시작하자.
global variables$를 이름앞에 붙인다.
instance variables@을 이름앞에 붙인다.
class variables@@을 이름앞에 붙인다.

local : name, fishAndChips, x_axis, thx1138, _26
global : $debug, $CUSTOMER, $_, $plan9, $Global
instance : @name, @point_1, @X, @_, @plan9
Class : @@total, @@symtab, @@N, @@x_pos, @@SINGLE
Constatns and Class Names : PI, FeetPerMile, String, MyClass, Jazz_Song


6. 배열과 해쉬

배열과 해쉬는 indexed collections이다. 둘다 key를 사용하여 접근 가능하다.
배열은 정수를 키로, 해쉬는 객체를 키로 사용한다.
이것들은 서로 다른타입을(integer, string, floating point number) 객체로 가질수 있다.

a = [1, 'cat', 3.14] # array with three elements
# access the first element
a[0]     >> 1
# set the third element
a[2] = nil
# dump out the array
a         >>  [ 1, "cat", nil]

Array.new를 사용하여 생성할 수도 있다.
empty1 = []
empty2 = Array.new

때때로 단어들을 사용하는 배열은 귀찮을 수가 있다. 왜냐 모두 quote로 묶어야 돼니까.
그걸위해 %w를 사용해라

a = %w{ ant bee cat dog elk }
a[0]    >> "ant"
a[3]    >> "dog"

해쉬를 사용하는 것은 배열과 비슷하다.

instSection = {
  'cello' => 'string',
  'clarinet' => 'woodwind',
  'drum => 'percussion',
  'oboe'  => 'woodwind',
  'trumpet' =>'brass',
  'violin'  => 'string'
}

instSection['oboe']  >> "woodwind:
instSection['cello']  >> "string"
instSection['bassoon'] >> nil

세번째 nil은 존재하지 않는다는 것을 의미한다.
nil은 조건식에서 false를 의미할 때 사용한다. 이 기본값을 바꾸길 원할것이다.
그거시 기본값으로 0을 가지긴 쉽다. 생성자로 생성할때 empty경우 기본값을 세팅하면 되거든

histogram = Hash.new(0)
histogram['key1']               >> 0
histogram['key1'] = histogram['key1'] + 1
histogram['key1']               >> 1

7. 조건문 반복문

일반적인 사용예)

if count > 10
  puts "Try again"
elsif tries == 3
  puts "You lose"
else
  puts "Enter a number"
end

while weight < 100 and numPallets <= 30
  pallet = nextPallet()
  weight += pallet.weight
  numPallets += 1
end

간단히 바꾸기
if radiation > 3000
  puts "Danger, Will Robinson"
end
=>
puts "Danger, Will Robinson" if radiation > 3000

while square < 1000
  square = square * square
end
=>
square = square*square while square < 1000


8. 정규표현식(Regualr Expressions)

/Perl|Python/  => /P(erl|ython)/
/\d\d:\d\d:\d\d/   # a time such as 12:34:56
/Perl.*Python/              # Perl, zero or more other chars, then Python
/Perl\s+Python/          # Perl, one or more spaces, then Python
/Ruby (Perl|Python)/    # Ruby, a space, and either Perl or Python

만약 해당되는 문자열이 =~ 다음에 포함되어 있으면(같은것이 아니고 포함) true, 아니면 false(nil)

line = 'Perl1'
if line =~ /Perl|Python/
  puts "aaa"
else
  puts "bbb"
end

>> aaa

문자열 변환

line = 'Perl123'
puts line.sub(/Perl/, 'Ruby')
>> Ruby123

9. Blocks and Iterators

{puts "Hello" }           # this is a block

do                            #
  club.enroll(person)  # and so is this
  person.socialize     #
end                         #

yield를 사용해서 method는 한번이상 invoke될수 있다.

def callBlock
  yield
  yield
end

callBlock { puts "In the block" }
>>
In the block
In the block

In the block이 두번 실행되엇다.
yield는 "|" 사이에 있는 파라미터를 받을수 있다.

def callBlock
  yield ,
end
callBlock { |, | ... }

Iterator사용
a = %w(ant bee cat dog elk)     # create an array
a.each {|animal| puts animal } # iterate over the contents
>>
ant
bee
cat
dog
elk


['cat','dog','horse'].each do |animal|
   print animal, " -- "
end
>> cat -- dog -- horse --

5.times {print "*"}
3.upto(6) {|i| print i}
('a'..'e').each{|char| print char}
>> *****3456abcde


10. Reading and 'Riting

printf "Number: %5.2f, String:%s", 1.23, "hello"
>> Number:  1.23, String:hello
C와 비슷

line = gets
print line

gets는 콘솔로부터 값을 받는구나


while gets
   if /Ruby/
     print
   end
end

이건 Ruby라는 단어를 치면 Ruby를 출력
>>
asdf
fds
sdf
g
Ruby
Ruby
asdf
Ruby
Ruby
ruby
Ruby
Ruby