練習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
110.
三元運算子 EXPRESSION ?(True Condition):(False Condition) a = 10 ; b = 100 a > b ? ( "#{a} > #{b}" ):( "#{a} < #{b}" ) #=> "10 < 100"
111.
迴圈 10 .times do puts ' 那很好啊 ' end for i in 1 .. 10 puts i end x = 100 while x > 10 x = x - 10 puts x end x = 100 until x <= 10 x = x – 10 next if x == 50 # 跳過下一步繼續 puts x end abc = [ 1 , 2 , 3 ] loop do abc.pop p abc break if abc.empty? # 跳出 end
定義類別 class Duck def initialize (name) @name = name end def quack # 實體方法 "#{ @name } is quacking!" end end d = Duck .new( ' 唐老鴨 !' ) puts d.quack # 唐老鴨 ! is quacking! 建構式 ! 物件實體變數
142.
定義類別 class Car @@amount = 0 def initialize (name) @name = name @@amount += 1 end def name= (val) @name = val end def name @name end def self . amount @@amount end end c1 = Car .new( ' 霹靂車 ' ); c2 = Car .new( ' 火戰車 ' ) c3 = Car .new( 'Focus' ); c3.name = 'Focus ST' puts " 現在有 " + Car .amount.to_s + " 台車了 " 物件類別變數 實體方法
143.
類別定義內也可以執行程式 class Car @@amount = 0 def initialize (name) @name = name @@amount += 1 end attr_accessor :name def self . amount @@amount end end class Car @@amount = 0 def initialize (name) @name = name @@amount += 1 end def name= (val) @name = val end def name @name end def self . amount @@amount end end =
私有/保護 定義方式 class Abc def pub ... end def priv ... end def prot ... end private :priv public :pub protected :prot end class Abc public def pub ... end private def priv ... end protected def prot ... end end =
繼承類別 class Vehicle attr_accessor :tires end class Tire attr_accessor :size 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
151.
探索繼承類別 c = Car .new( 'Mondeo 2.0' ) puts c.is_a?( Vehicle ) #true puts c.class.superclass #Vehicle
152.
走訪迴圈 langs =[ 'VB' , 'C#' , 'C' , 'JavaScript' ] langs.each do |lang| puts " 我會 #{lang}" end 輸出: # 我會 VB # 我會 C# # 我會 C # 我會 JavaScript
練習4 class String def find_capital_letters s2r = '' self .each_char{|c| cc = c[ 0 ].to_i s2r.concat(c) if cc >= 65 && cc <= 90 } return s2r end end puts 'SUSE Linux' .find_capital_letters
171.
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!
172.
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 SingletonClass 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"/> 我是圖片
186.
Module for Namespacemodule Forum class Member # 類別全名為 Forum::Member .... end class Topic #Forum::Topic end end
187.
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 間接實現了 多重繼承
188.
動態型別 (duck typing)不管黑貓白貓,會抓老鼠的都是好貓 class PersianCat def find_mice # 抓老鼠 end end class RussianBlueCat def find_mice # 抓老鼠 end end
define_method class Movie def initialize (id, name) @id = id @name = name end 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 return "/movies/#{qt.to_s}/#{ @id }.mp4" end end end a = Movie .new( 123 , ' 阿凡達 ' ) puts a.hd_movie_file #/movies/hd/123.mp4
192.
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 HTTP 動詞對應網址樣式, 即可做 WEB 伺服器的處理
193.
Method Missing class Wheel attr_accessor :radius def initialize (radius) @radius = radius end end 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> Car 並不預設 wheel_1 執行 method_missing
練習5 class TextFileSearcher def initialize (fn) @file_path = fn end def search_word (word) open( @file_path , 'r' ) do |fc| while line = fc.gets line.downcase! ar = line.scan(word.to_s) unless ar.empty? puts "#{line} meets #{word} #{ar.size} times." end end end end end tt = TextFileSearcher .new( 'r.txt' ) tt.search_word( 'ruby' )
傳遞變數到 Template get '/array' do @arr = [ "aaa" , "bbb" , "ccc" , "ddd" ] erb :array end <% @arr .each do |item| %> <p> <%= item %> </p> <% end %>
232.
POST FORM get '/' do erb :index end post '/query' do params[ :keyword ] end <form action = "/query" method = "post" > <p><input type = "text" name = "keyword" value = "" ></p> <p><input type = "submit" value = "Submit" ></p> </form>
練習6 #t6.rb require 'rubygems' require 'sinatra' get '/' do erb :index end post '/' do @text = params[ :text2parse ].gsub(params[ :word ], "<b>#{params[ :word ]}</b>" ) erb :post end
239.
練習6 #index.erb <form action = "/" method = "post" > <input type = "text" name = "word" value = "" /><br/> <textarea name = "text2parse" cols = "100" rows = "20" ></textarea><br/> <input type = "submit" value = " 送出 " /> </form> #post.erb <p> <%= @text %> </p>
建立DB 編輯 db/migrate下的第一個 .rb class CreatePosts < ActiveRecord :: Migration def self . up create_table :posts do |t| t.string :author t.string :subject t.text :message t.timestamps end end def self . down drop_table :posts end end
也DSL化 namespace :gameclub do desc " 自動移除論壇的操作 " task :daily_remove => :environment do Billboard .should_remove.each do |bbs| if bbs.destroy puts " 成功刪除論壇 ID#{bbs.id}, #{bbs.full_url}" else puts " 刪除論壇 ID#{bbs.id}, #{bbs.full_url} 失敗 !" end end end end rake gameclub:daily_remove
7 Actions URLVERB 用途 /posts get 列表 /posts post 建立新留言 /posts/:id get show完整留言 /posts/:id/edit get 進入編輯頁 /posts/:id put 提交修改 /posts/:id/delete get 刪除 /posts/new get 新增頁面
277.
REST-STYLE URL PATTERNURL 行為 實體/類別 VERB /posts 無 類別 get /posts 無 類別 post /posts/:id 無 實體 get /posts/:id/edit edit 實體 get /posts/:id 無 實體 put /posts/:id/delete delete 實體 get /posts/new new 類別 get
require必要的lib require 'rubygems' require 'sinatra' require 'active_record' $DBCONFIG = YAML ::load File .open( "config/database.yml" , 'r' ).read ActiveRecord :: Base .establish_connection $DBCONFIG [ "development" ] Dir .glob( 'app/models/*.rb' ).each{ |f| require f} get '/' do redirect '/posts' end
280.
CONTROLLER get '/posts/new' do #new @post = Post .new erb :new end get '/posts' do #list @posts = Post .all erb :index end
281.
CONTROLLER put '/posts/:id' do #update puts " 到了 put #{params.inspect}" @post = Post .find(params[ :id ].to_i) if @post .update_attributes( :author => params[ :author ], :subject => params[ :subject ], :message => params[ :message ]) p @post redirect "/posts" else erb :edit end end
282.
CONTROLLER get '/posts/:id' do #show @post = Post .find(params[ :id ].to_i) erb :show end get '/posts/:id/delete' do #delete @post = Post .find(params[ :id ].to_i) @post .destroy redirect "/posts" end post '/posts' do #create puts " 建文章 " @post = Post .new( :author => params[ :author ], :subject => params[ :subject ], :message => params[ :message ]) if @post .save redirect "/posts" else erb :new end