ruby 入門 第一次就上手
Post on 12-Sep-2014
8.963 views
DESCRIPTION
TRANSCRIPT
Ruby 程式語言第一次就上手
http://creativecommons.org/licenses/by-nc/2.5/tw/
我是誰?• 張文鈿 a.k.a. ihower
• http://ihower.idv.tw/blog/
• http://twitter.com/ihower
• 從 2006 年開始使用 Ruby
• 和多(股)公司 Rails Developer
• http://handlino.com
• http://registrano.com
誰是助教?
• 鄧慕凡 a.k.a Ryudo
• http://www.freebbs.tw
• http://www.gameckub.tw
• 從2007開始使用Rails
• TOMLAN軟體工作室 FOUNDER
什麼是 Ruby?
• 開放原碼、物件導向的動態直譯式(interpreted)程式語言
• 簡單哲學、高生產力• 精巧、自然的語法• 創造者 Yukihiro Matsumoto, a.k.a. Matz
• 靈感來自 Lisp, Perl, 和 Smalltalk
• 設計的目的是要讓程式設計師 Happy
安裝環境
• 下載安裝 Ruby 1.8.6 One-click Installer
• http://www.ruby-lang.org/en/downloads/
• Next -> Agree -> 勾選 Enable Rubygems
Part1: 基礎語法
irb: Interactive Ruby馬上動手練習
irb(main):001:0>
irb(main):001:0> 1 + 1=> 2
irb(main):002:0> 100 * 5 + 99
PUTS 螢幕輸出
• 打開 notepad++,編輯 hello.rb
• 執行 ruby number.rb
puts "Hello World!"
整數 Integer
5-20599999999990
浮點數 Float後面有 .
54.3210.001-12.3120.0
浮點數四則運算
puts 1.0 + 2.0puts 2.0 * 3.0puts 5.0 - 8.0puts 9.0 / 2.0
# 3.0# 6.0# -3.0# 4.5
整數四則運算結果也會是整數
puts 1 + 2puts 2 * 3puts 5 - 8puts 9 / 2
# 3# 6# -1# 4
更多運算
puts 5 * (12-8) + -15puts 98 + (59872 / (13*8)) * -52
字串 String
puts 'Hello, world!'puts ''puts 'Good-bye.'
字串處理
puts 'I like ' + 'apple pie.'puts 'You\'re smart!'
puts '12' + 12 #<TypeError: can't convert Fixnum into String>
變數 Variable
composer = 'Mozart'puts composer + ' was "da bomb", in his day.'
composer = 'Beethoven'puts 'But I prefer ' + composer + ', personally.'
型別轉換 Conversions
var1 = 2var2 = '5'
puts var1.to_s + var2 # 25puts var1 + var2.to_i # 7
puts 9.to_f / 2 # 4.5
GETS 螢幕輸入
puts 'Hello there, and what\'s your name?'
name = gets.chomp
puts 'Your name is ' + name + '? What a lovely name!'puts 'Pleased to meet you, ' + name + '. :)'
函式呼叫 Methods
• 所有東西都是物件(Object),例如字串、整數、浮點數。
• 透過逗點 . 來對物件呼叫函式
• 沒有逗點的函式呼叫,預設了 self。例如 puts 就是 self.puts 的意思。
更多字串函式
var1 = 'stop'var2 = 'foobar'var3 = "aAbBcC"
puts var1.reverse # 'pots'puts var2.length # 6puts var3.upcaseputs var3.downcase
流程控制 Flow Control
比較函式
puts 1 > 2puts 1 < 2puts 5 >= 5puts 5 <= 4puts 1 == 1puts 2 != 1
puts ( 2 > 1 ) && ( 2 > 3 ) # andputs ( 2 > 1 ) || ( 2 > 3 ) # or
真或假只有 false 和 nil 是假,其他為真
puts "not execute" if nilputs "not execute" if false
puts "execute" if true # 輸出 executeputs "execute" if “” # 輸出 execute (和JavaScript不同)puts "execute" if 0 # 輸出 execute (和C不同)puts "execute" if 1 # 輸出 executeputs "execute" if "foo" # 輸出 executeputs "execute" if Array.new # 輸出 execute
條件分支puts "hello, who are you?"
name = gets.chomp
if name == "you" puts "that's you"elsif name == "me" puts "that's me"else puts "no ideas"end
控制結構 Case
case name when "John" puts "Howdy John!" when "Ryan" puts "Whatz up Ryan!" else puts "Hi #{name}!"end
迴圈
command = ''
while command != 'bye' puts command command = gets.chompend
puts 'Come again soon!'
陣列 Array
a = [ 1, "cat", 3.14 ]
puts a[0] # 輸出 1puts a[1] # 輸出 “cat”puts a.size # 輸出 3
更多陣列函式
colors = ["red", "blue"]
colors.push("black")colors << "white"puts colors.join(", ") # red, blue, black, white
colors.popputs colors.last #black
走訪迴圈 each method
languages = ['Ruby', 'Javascript', 'Perl']
languages.each do |lang| puts 'I love ' + lang + '!'end
# I Love Ruby# I Love Javascript# I Love Perl
迭代器 iterator
• 不同於 while 迴圈用法,each 是一個陣列的函式,走訪其中的元素,我們稱作迭代器(iterator)
• 其中 do .... end 是 each 函式的參數,稱作匿名函式( code block)
最簡單的迭代器
3.times do puts 'Good Job!'end
# Good Job!# Good Job!# Good Job!
code block一種匿名函式,或稱作 closure
{ puts "Hello" } # 這是一個 block
do puts "Blah" # 這也是一個 block puts "Blah"end
code block其他走訪方式
# 走訪並造出另一個陣列a = [ "a", "b", "c", "d" ]b = a.map {|x| x + "!" }puts b.inspect# 結果是 ["a!", "b!", "c!", "d!"]
# 找出符合條件的值b = [1,2,3].find_all{ |x| x % 2 == 0 }b.inspect# 結果是 [2]
code block僅執行一次呼叫
file = File.new("testfile", "r")# ...處理檔案file.close
File.open("testfile", "r") do |file| # ...處理檔案end# 檔案自動關閉
雜湊 Hash(Associative Array)
config = { "foo" => 123, "bar" => 456 }
puts config["foo"] # 輸出 123
字串符號 Symbols唯一且不會變動的識別名稱
config = { :foo => 123, :bar => 456 }
puts config[:foo] # 輸出 123
定義函式 Methodsdef 開頭 end 結尾
def say_hello(name) result = "Hi, " + name return resultend
puts say_hello('ihower')# 輸出 Hi, ihower
定義函式 Methodsdef 開頭 end 結尾
def say_hello(name) result = "Hi, " + name return resultend
puts say_hello('ihower')# 輸出 Hi, ihower
字串相加
類別與物件類別 Class
屬性Attributes
函式Methods
物件 Object
屬性Attributes
函式Methods
物件 Object
屬性Attributes
函式Methods
Person
john = Person.new mary = Person.new
類別 Classes大寫開頭,使用 new 可以建立出物件
color_string = String.new color_string = "" # 等同
color_array = Array.newcolor_array = [] # 等同
color_hash = Hash.newcolor_hash = {} # 等同
time = Time.newputs time
建立自己的類別class Greeter
def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end
g1 = Greeter.new("ihower")g2 = Greeter.new("ihover") g1.say("Hello") # 輸出 Hello, ihowerg2.say("Hello") # 輸出 Hello, ihover
建立自己的類別class Greeter
def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end
g1 = Greeter.new("ihower")g2 = Greeter.new("ihover") g1.say("Hello") # 輸出 Hello, ihowerg2.say("Hello") # 輸出 Hello, ihover
建構式
建立自己的類別class Greeter
def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end
g1 = Greeter.new("ihower")g2 = Greeter.new("ihover") g1.say("Hello") # 輸出 Hello, ihowerg2.say("Hello") # 輸出 Hello, ihover
建構式
物件變數
建立自己的類別class Greeter
def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end
g1 = Greeter.new("ihower")g2 = Greeter.new("ihover") g1.say("Hello") # 輸出 Hello, ihowerg2.say("Hello") # 輸出 Hello, ihover
建構式
物件變數
字串相加(內插法)
類別函式
class Greeter
@@name = “ihower” def self.say puts @@name end end
Greeter.say # 輸出 Hello, ihower
類別函式
class Greeter
@@name = “ihower” def self.say puts @@name end end
Greeter.say # 輸出 Hello, ihower
類別變數
類別函式
class Greeter
@@name = “ihower” def self.say puts @@name end end
Greeter.say # 輸出 Hello, ihower
類別變數
類別函式
建立物件變數的存取函式attr_accessor, attr_writer, attr_reader
class Person attr_accessor :name end
class Person
def name @name end def name=(val) @name = val end end
等同於
Part2: 應用練習gem install sinatra -y --no-ri --no-rdoc
gem install nokogiri -y --no-ri --no-rdoc
RubyGems
• Ruby 的套件管理工具
• gem list 可以顯示目前安裝的套件
• 更多套件 http://gemcutter.org/
Sinatra
• 一套非常輕量的 web development 工具
• http://www.sinatrarb.com/
• gem install sinatra
第一隻 web app執行 ruby myapp.rb,然後打開瀏覽器 http://localhost:4567
# myapp.rbrequire 'rubygems'require 'sinatra'
get '/' do 'Hello world!'end
傳遞 URL 參數
require 'rubygems'require 'sinatra'
get '/hello/:name' do # 符合 "GET /hello/foo" 或 "GET /hello/bar" # params[:name] 就會是 'foo' 或 'bar' "Hello #{params[:name]}!"end
使用 template建立 views 目錄,加入 hello.erb 檔案
# myapp.rbrequire 'rubygems'require 'sinatra'
get '/hello/:name' do erb :helloend
ERB (Ruby Template)<!DOCTYPE html><html><head> <title>Sinatra app</title></head><body> <% 10.times do %> <p><%= "Hello #{params[:name]}!" %></p> <% end %> </body></html>
傳遞變數到 Template# myapp.rbrequire 'rubygems'require 'sinatra'
get '/array' do @arr = ["aaa","bbb","ccc","ddd"] erb :arrayend
# views/array.erb<% @arr.each do |item| %> <p><%= item %></p><% end %>
表單製作
# views/index.erb<form action="/query" method="post">
<p><input type="text" name="keyword" value=""></p> <p><input type="submit" value="Submit"></p>
</form>
# myapp.rbrequire 'rubygems'require 'sinatra'
get '/' do erb :indexend
post '/query' do params[:keyword]end
nokogiri
• HTML, XML, SAX 解析工具 (parser)
• 使用 XPath 或 CSS 選取想要的資料
• gem install nokogiri
require 'rubygems'require 'nokogiri'
text = "<html> <ul> <li>FOOOBARRR</li> <li>AAAAACCCCC</li> <ul></html>"
doc = Nokogiri::HTML(text)
puts doc.css('li').size # 2
doc.css('li').each do |item| puts item.contentend
# FOOOBARRR# AAAAACCCCC
sinatra+nokogiri 應用抓取目標網頁的所有超連結
# myapp.rbrequire 'rubygems'require 'sinatra'require 'nokogiri'require 'open-uri'
get '/' do erb :indexend
post '/query' do html = open( params[:keyword] ).read doc = Nokogiri::HTML(html) @links = doc.css('a') erb :queryend
<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><ul><% @links.each do |link| %> <li> <%= link.content %> <%= link.attributes["href"] %> </li><% end %></ul>
</body>
Thank you.
參考資料:Learn to Program http://pine.fm/LearnToProgram/Beginning Ruby 2nd. (Apress)