ruby study 2

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

루비의 정규표현식

 

/pattern/

=~ : 패턴 비교 operator

 

if line =~ /Perl/

           puts "#{line}"

end

 

line.sub(/Perl/, 'Ruby') # 첫번째 Perl 문자를 Ruby 로 변경한다.

line.gsub(/Perl/, 'Ruby') # 모든 Perl 문자를 Ruby 로 변경한다.

 

Block

 

Block 이란

 

1. { puts "Hello" } : {} 로 감싸진 부분

2. do

           club.enroll(person)

           person.socialize

           end

           : do ~ end 부분도 Block 이다.

          

yield 명령어는 함수로 넘겨진 Block 을 실행한다.

 

def callBlock

           yield

           yield

end

 

callBlock { puts "In the block" }

=>

In the block

In the block

 

# Array 클래스의 each 메소드

def each

  for each element

    yield(element) # 이부분이 block 으로 인자를 넘기는 부분이다.

  end

end

 

a = %w( ant bee cat dog elk )    # 문자열 배열 생성

a.each { |animal| puts animal }  # block 에서 인자는 |arg| 로 받게 된다.

 

=>

ant

bee

cat

dog

elk

 

5.times {  print "*" }

3.upto(6) {|i|  print i }

('a'..'e').each {|char| print char }

 

=> *****3456abcde

 

Reading and 'Riting

 

printf 명령어

printf "Number: %5.2f, String: %s", 1.23, "hello"

=> Number: 1.23, String: hello

 

사용자의 입력을 받는방법

line = gets

print line

 

# 사용자의 입력을 받아서 /Ruby/ 정규 표현식과 비교해 매치되면 출력하는 코드

while gets

           if /Ruby/

                     print

           end

end

 

위와 동일한 코드

=> ARGF.each{ |line| print line if line =~ /Ruby/ }

 

 

Classes, Objects, and Variables

 

class Song

           def initialize(name, artist, duration)

                     @name = name

                     @artist = artist

                     @duration = duration

           end

end

 

class Song : 클래스명의 첫글자는 대문자로 표기

initialize 메소드 : initialize 메소드는 Song.new 로 인스턴스 생성시 자동으로 호출되는 메소드

name, artist, duration : 로컬 변수, 소문자로 표기

@name, @artist, @duration : 인스턴스 변수, 소문자로 표기

 

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

aSong.inspect >> #<Song:0x2bb680c @duration=260, @artist="Fleck", @name="Bicyclops">

 

to_s : Ruby 의 객체들은 to_s 메소드를 호출하여 객체의 일반적인 메세지를 출력할 수 있다. 재정의를 하지 않으면 객체의 object_id 를 출력한다.

 

Inheritance and Message

 

class KaraokeSong < Song

  def initialize (name, artist, duration, lyrics)

    super( name, artist, duration)

    @lyrics = lyrics

  end

 

  def to_s

    super + "[#{@lyrics}]"

  end

end

 

aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...") 

aSong.to_s => "KS: My Way--Sinatra (225) [And now, the...]" 

 

Object and Attribute

 

def name

           @name

end

 

def artist

           @artist

end

 

def duration

           @duration

end

 

instance 변수에 접근하기 위해서는 관련 메소드를 정의해 주어야 한다.

=====================================

 

attr_reader :name, :artist, :duration

attr_reader 명령어 : 해당 명령어를 사용하면 instance 변수를 접근하기 위한 메소드가 자동으로 생성된다.

 

Writable Attribute

 

instance 변수에 값을 지정하기 위해서는 instance 변수이름= 메소드를 정의해야 한다.

 

def name=(newName)

           @name = newName

end

 

name= 이 변수이름이며 aSong="newName" 으로 호출된다.

=====================================

 

attr_writer :name

attr_writer 명령어 : 해당 명령어를 사용하면 instance 변수에 값을 할당하기 위한 메소드가 자동으로 생성된다.

 

Virtual Attributes

 

def durationInMinutes 

           @duration/60.0   # force floating point 

end 

def durationInMinutes=(value) 

           @duration = (value*60).to_i 

end 

 

aSong.durationInMinutes

aSong.durationInMinutes=4.2

aSong.duration

 

Class Variables and Class Method

 

클래스 변수

- 클래스 변수는 해당 클래스에서 생성된 모든 인스턴스들이 공유하게 된다. 클래스 변수는 @@ 로 시작한다.

 

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)

s2 = Song.new("Song2", "Artist2", 345)

puts s1.play

puts s2.play

puts s1.play

puts s2.play

 

클래스 메소드

 

Song.new(...)

 

여기서 new 는 클래스 메소드이다.

 

class Example

  def instMeth              # 인스턴스 메소드

  end

 

  def Example.classMeth     # 클래스 메소드

  end

end

 

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

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

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