22. 練習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 + '. :)'
46. 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"
56. randnum = 0
loop do
randnum = rand(20)
break if randnum > 0
end
5.times do
print '請輸⼊入⼀一個數字:'
num = gets.chomp.to_i
if num == randnum
puts '猜對了~YEAH!'
break
end
if num - randnum >= 10
puts "猜的⼤大很多"
elsif (num - randnum) < 10 && (num - randnum) >= 1
puts '猜的⼤大⼀一點'
elsif randnum - num >= 10
puts '猜的⼩小很多'
else
puts '猜的⼩小⼀一點'
end
end
73. 私有/保護 定義方式
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
75. 繼承類別
class Vehicle
attr_accessor :tires
end
class Car < 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
99. Module for Singleton Class
module HtmlHelper
HTML_ESCAPE = { '&' => '&', '>' =>
'>', '<' => '<', '"' => '"' }
def self.h(s)
s.to_s.gsub(/[&"><]/){ |special|
HTML_ESCAPE[special] }
end
end
puts HtmlHelper.h('<img src="abc.gif"/>我是圖⽚片')
#<img src="abc.gif"/>我是圖⽚片
100. Module for Namespace
module Forum
class Member
#類別全名為 Forum::Member
....
end
class Topic
#Forum::Topic
end
end
101. Module for Mix-in
多重繼承之實現
module ShareMod
def subject
...
end
end
class Forum
include ShareMod
end
class SubForum
include ShareMod
end
#Foum和SubForum都會有subject的instance method
105. 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>