12 루비(Ruby) 프로그래밍
http://benelog.springnote.com/pages/84624/attachments/30264
http://shampu.clus.org/tc/Shampu/363
http://ruby.about.com/od/tk/a/Tk.htm
@ruby 책
http://www.ruby-doc.org/docs/ProgrammingRuby/
*.화면 출력
1.메시지 출력
puts "Hello World"
2.메시지 연결
puts "Hello" + "World"
3.메시지에 변수 출력
message = "Hello World"
puts "my Message is #{message}"
*.Array 다루기
1.빈 Array 만들기
empty1 = []
empty2 = Array.new
2.문자열을 쉽게 Array로 바꾸기
a = %w{ ant bee cat dob elk }
=> ["ant", "bee", "cat", "dob", "elk"]
a[0] » "ant"
a[3] » "dog"
3.Hash 쓰기
instSection = {
'cello' => 'string',
'clarinet' => 'woodwind',
'drum' => 'percussion',
'oboe' => 'woodwind',
'trumpet' => 'brass',
'violin' => 'string'
}
instSection['oboe'] » "woodwind"
instSection['cello'] » "string"
instSection['bassoon'] » nil
histogram = Hash.new(0)
histogram['key1'] » 0
histogram['key1'] = histogram['key1'] + 1
histogram['key1'] » 1
4.범위 안에 데이터를 모두 Array로 만들기
(0..10).to_a
=>[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
5.3x3 2차원 Array 만들기
doublearray = []
doublearray[0] = (0..2).to_a
doublearray[1] = (3..5).to_a
doublearray[2] = (6..8).to_a
doublearray
=> [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
*.제어문
1.if 문 사용법
if count > 10
puts "Try again"
elsif tries == 3
puts "You lose"
else
puts "Enter a number"
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
1.Case문
irb(main):023:0> a = 2
=> 2
irb(main):024:0> case a
irb(main):025:1> when 1; puts 1
irb(main):026:1> when 2; puts 2
irb(main):027:1> end
2
=> nil
caes문을 사용할 때 꼭 case에 넘겨주는 변수가 없어도 됩니다. 그렇게하면 차례로 when 문이 실행되므로 가장 처음 참인 문장이 실행되고 빠지게 됩니다. 예를들면,
irb(main):028:0> a = 2
=> 2
irb(main):029:0> case
irb(main):030:1* when a == 1; puts 1
irb(main):031:1> when a == 2; puts 2
irb(main):032:1> when a == 3; puts 3
irb(main):033:1> end
2.Loop
irb(main):003:0> for i in list
irb(main):004:1> puts i if i % 5 == 0
irb(main):005:1> end
5
10
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):006:0>
range로도 가능합니다.
irb(main):006:0> for i in (1..10)
irb(main):007:1> puts i if i % 5 == 0
irb(main):008:1> end
5
10
=> 1..10
irb(main):009:0>
여기서 (1..10)이 1부터 10까지의 range죠. range는 쉽게 list로 바꿀 수 있습니다.
irb(main):009:0> (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):010:0>
3.가변 인자
이외에도, 매개변수에 기본 값을 준다던가 또는 임의 개수의 인자를 받는 다던가 하는 것도 가능합니다. 임의 개수의 인자를 받는 부분을 보죠.
http://www.ibm.com/developerworks/kr/library/x-rubytextproc/index.html
irb(main):029:0> def g(*args)
irb(main):030:1> a1, a2 = args[0], args[1]
irb(main):031:1> puts a1
irb(main):032:1> puts a2
irb(main):033:1> end
=> nil
irb(main):034:0> g(1,2)
1
2
=> nil
irb(main):035:0>
*args로 쓰면 인자를 리스트로 받게 됩니다.
한편 루비는 position에 의해 인자를 구분합니다. 함수에 준 첫번째 인자는 함수의 첫번째 매개변수에 들어가고, 두번째 인자는 함수의 두번째 인자에 들어가죠. 그러나 해싱을 사용해 named parameter를 구현할 수 있습니다. 방법은, 함수의 마지막 인자가 해시일때는 { } 를 사용해 명시적으로 해당 인자가 해시임을 지정하지 않아도 된다는 점을 이용하는 것입니다.
irb(main):006:0> def f(opt, vars)
irb(main):007:1> a1, a2 = vars[:a1], vars[:a2]
irb(main):008:1> puts "opt = #{opt}\ta1 = #{a1}\ta2 = #{a2}"
irb(main):009:1> end
=> nil
irb(main):010:0> f(1, :a1=> 1, :a2 => 2)
opt = 1 a1 = 1 a2 = 2
=> nil
irb(main):011:0>
4.정규표현식
http://www.rubyist.net/~slagell/ruby/regexp.html
You can also match one of a group of characters within a pattern. Some common examples are character classes such as ``\s'', which matches a whitespace character (space, tab, newline, and so on), ``\d'', which matches any digit, and ``\w'', which matches any character that may appear in a typical word. The single character ``.'' (a period) matches any character.
/\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
정규 표현식을 이용한 문자열 매칭 여부 비교시 =~ 사용 가능
if line =~ /Perl|Python/
puts "Scripting language mentioned: #{line}"
end
line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'
line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'
*.Code Block 사용법
def callBlock
yield
yield
end
callBlock { puts "In the block" }
produces:
In the block
In the block
5.times { print "*" }
3.upto(6) {|i| print i }
('a'..'e').each {|char| print char }
produces:
*****3456abcde
*.화면 입출력
printf "Number: %5.2f, String: %s", 1.23, "hello"
Number: 1.23, String: hello
line = gets
print line
while gets # assigns line to $_
if /Ruby/ # matches against $_
print # prints $_
end
end
키보드로 입력을 매 라인마다 받아서 입력 값이 Ruby일 때 화면에 출력하는 예제
ARGF.each { |line| print line if line =~ /Ruby/ }
5.if문
if count > 10
puts "Try again"
elsif tries == 3
puts "You lose"
else
puts "Enter a number"
end
0.두 개 이상의 리턴값 전달하기 및 받기
def function
return [0, 1]
end
a,b = function()
*.class 처리
class Song
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
end
aSong = Song.new("Bicylops", "Fleck", 260) |
||
aSong.inspect |
» | "#<Song:0x401b4924 @duration=260, @artist=\"Fleck\", @name=\"Bicylops\">" |
inspect는 Object의 모든 변수와 ID를 반환
class Song |
||
def to_s |
||
"Song: #{@name}--#{@artist} (#{@duration})" |
||
end |
||
end |
||
aSong = Song.new("Bicylops", "Fleck", 260) |
||
aSong.to_s |
» | "Song: Bicylops--Fleck (260)" |
to_s Method를 재정의
상속~!!!
class KaraokeSong < Song
def initialize(name, artist, duration, lyrics)
super(name, artist, duration)
@lyrics = lyrics
end
end
상위 함수 호출
class KaraokeSong < Song |
||
# Format ourselves as a string by appending |
||
# our lyrics to our parent's #to_s value. |
||
def to_s |
||
super + " [#{@lyrics}]" |
||
end |
||
end |
||
aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...") |
||
aSong.to_s |
» | "Song: My Way--Sinatra (225) [And now, the...]" |
변수와 같은 이름의 함수를 정의하여 변수에 접근할 수 있도록 하는 방법
class Song |
||
def name |
||
@name |
||
end |
||
def artist |
||
@artist |
||
end |
||
def duration |
||
@duration |
||
end |
||
end |
||
aSong = Song.new("Bicylops", "Fleck", 260) |
||
aSong.artist |
» | "Fleck" |
aSong.name |
» | "Bicylops" |
aSong.duration |
» | 260 |
변수 속성 관리 방법
class Song
attr_reader :name, :artist, :duration
attr_writer :duration
attr_accessor :something
end
class Method와 Variable
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
class Example
def instMeth # instance method
end
def Example.classMeth # class method
end
end
class SongList |
||
MaxTime = 5*60 # 5 minutes |
||
def SongList.isTooLong(aSong) |
||
return aSong.duration > MaxTime |
||
end |
||
end |
class 접근 제한자
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
History
Last edited on 10/26/2011 01:38 by kkamagui
Comments (0)