練習1
puts 'Hello there,and what's your name?'
name = gets.chomp
puts 'Your name is ' + name + '? What a nice
name!'
puts 'Pleased to meet you, ' + name + '. :)'
CASE
aaa = [1,'abc', 1.3]
p aaa
printf('你要確認哪⼀一個?')
idx = gets.to_i
case aaa[idx]
when String
puts "這是⼀一個字串"
when Integer
puts "這是⼀一個整數"
when Float
puts "這是⼀一個浮點數"
when Numeric
puts '這是⼀一個數字'
else
puts "這是其它類型的物件"
end
47.
三元運算子
EXPRESSION
?
(True
Condition):(False
Condition)
a = 10; b = 100
a > b ? ("#{a} > #{b}"):("#{a} < #{b}") #=> "10 <
100"
私有/保護 定義方式
class Hoge< HogeSuper
def hoge
protected_method # OK
private_method # OK
a = Hoge.new
a.protected_method # OK
a.private_method # Error
end
end
Hoge.new.hoge
繼承類別
class Vehicle
attr_accessor :tires
end
classCar < Vehicle
def initialize(name)
@tires = []
4.times{@tires << Tire.new}
end
end
class Motorcycle < Vehicle
def initialize(name)
@tires = []
2.times{@tires << Tire.new}
end
end
Yield and Method
在函式中使用yield 來執行 code block
def test_block
puts "I love Ruby ,"
yield
end
test_block{ puts 'Ruby loves
programmers!'}
#顯⽰示
I love Ruby ,
Ruby loves programmers!
92.
Yield and Method
在函式中使用yield 來執行 code block
def to_div(times)
buffer = '<DIV>'
times.times{|x| yield(buffer, x)}
buffer.concat '</DIV>'
end
divhtml = to_div(3) do |buf, x|
buf.concat "<p>No.#{x+1}</p>"
end
puts divhtml
#
<DIV><p>No.1</p><p>No.2</p><p>No.3</p></DIV>
Module for Namespace
moduleForum
class Member
#類別全名為 Forum::Member
....
end
class Topic
#Forum::Topic
end
end
101.
Module for Mix-in
多重繼承之實現
moduleShareMod
def subject
...
end
end
class Forum
include ShareMod
end
class SubForum
include ShareMod
end
#Foum和SubForum都會有subject的instance method
define_method
class Movie
def initialize(id,name)
@id = id;@name = name
end
def movie_file(quality)
"/movies/#{quality}/#{@id}.mp4"
end
end
a = Movie.new(123,'阿凡達')
puts a.movie_file(:hd) #/movies/hd/123.mp4
puts a.movie_file(:sd) #/movies/sd/123.mp4
106.
class Movie
QualityNames =[:fullhd, :hd, :sd]
#定義 fullhd_movie_file, hd_movie_file,
sd_movie_file
#三個⽅方法
QualityNames.each do |qt|
define_method "#{qt.to_s}_movie_file".to_sym
do
"/movies/#{qt.to_s}/#{@id}.mp4"
end
end
end
a = Movie.new(123,'阿凡達')
puts a.hd_movie_file #/movies/hd/123.mp4
puts a.sd_movie_file #/movies/sd/123.mp4
107.
Domain-Specific Language
領域特定語言
Class MyApp< Sinatra::Base
get '/books/*.*' do
# matches /books/ruby-guide.html
end
get '/rooms/:id/index.html' do
# matches '/rooms/123/index.html
end
end
108.
Method Missing
class Car
attr_accessor:wheels
def initialize
@wheels = []
4.times{@wheels << Wheel.new(30)}
end
def method_missing(mname, *args)
if mname.to_s =~ /wheel_(d)/
return @wheels[$1.to_i]
end
end
end
my_car = Car.new
p my_car.wheel_1 #<Wheel:0x8f6dea4 @radius=30>