ruby 入門 第一次就上手

62
Ruby 程式語言 第一次就上手 [email protected] http://creativecommons.org/licenses/by-nc/2.5/tw/

Post on 12-Sep-2014

8.963 views

Category:

Documents


2 download

DESCRIPTION

 

TRANSCRIPT

Page 2: Ruby 入門 第一次就上手

我是誰?• 張文鈿 a.k.a. ihower

• http://ihower.idv.tw/blog/

• http://twitter.com/ihower

• 從 2006 年開始使用 Ruby

• 和多(股)公司 Rails Developer

• http://handlino.com

• http://registrano.com

Page 3: Ruby 入門 第一次就上手

誰是助教?

• 鄧慕凡 a.k.a Ryudo

• http://www.freebbs.tw

• http://www.gameckub.tw

• 從2007開始使用Rails

• TOMLAN軟體工作室 FOUNDER

Page 4: Ruby 入門 第一次就上手

什麼是 Ruby?

• 開放原碼、物件導向的動態直譯式(interpreted)程式語言

• 簡單哲學、高生產力• 精巧、自然的語法• 創造者 Yukihiro Matsumoto, a.k.a. Matz

• 靈感來自 Lisp, Perl, 和 Smalltalk

• 設計的目的是要讓程式設計師 Happy

Page 5: Ruby 入門 第一次就上手

安裝環境

• 下載安裝 Ruby 1.8.6 One-click Installer

• http://www.ruby-lang.org/en/downloads/

• Next -> Agree -> 勾選 Enable Rubygems

Page 6: Ruby 入門 第一次就上手

Part1: 基礎語法

Page 7: Ruby 入門 第一次就上手

irb: Interactive Ruby馬上動手練習

irb(main):001:0>

irb(main):001:0> 1 + 1=> 2

irb(main):002:0> 100 * 5 + 99

Page 8: Ruby 入門 第一次就上手

PUTS 螢幕輸出

• 打開 notepad++,編輯 hello.rb

• 執行 ruby number.rb

puts "Hello World!"

Page 9: Ruby 入門 第一次就上手

整數 Integer

5-20599999999990

Page 10: Ruby 入門 第一次就上手

浮點數 Float後面有 .

54.3210.001-12.3120.0

Page 11: Ruby 入門 第一次就上手

浮點數四則運算

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

Page 12: Ruby 入門 第一次就上手

整數四則運算結果也會是整數

puts 1 + 2puts 2 * 3puts 5 - 8puts 9 / 2

# 3# 6# -1# 4

Page 13: Ruby 入門 第一次就上手

更多運算

puts 5 * (12-8) + -15puts 98 + (59872 / (13*8)) * -52

Page 14: Ruby 入門 第一次就上手

字串 String

puts 'Hello, world!'puts ''puts 'Good-bye.'

Page 15: Ruby 入門 第一次就上手

字串處理

puts 'I like ' + 'apple pie.'puts 'You\'re smart!'

puts '12' + 12 #<TypeError: can't convert Fixnum into String>

Page 16: Ruby 入門 第一次就上手

變數 Variable

composer = 'Mozart'puts composer + ' was "da bomb", in his day.'

composer = 'Beethoven'puts 'But I prefer ' + composer + ', personally.'

Page 17: Ruby 入門 第一次就上手

型別轉換 Conversions

var1 = 2var2 = '5'

puts var1.to_s + var2 # 25puts var1 + var2.to_i # 7

puts 9.to_f / 2 # 4.5

Page 18: Ruby 入門 第一次就上手

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 + '. :)'

Page 19: Ruby 入門 第一次就上手

函式呼叫 Methods

• 所有東西都是物件(Object),例如字串、整數、浮點數。

• 透過逗點 . 來對物件呼叫函式

• 沒有逗點的函式呼叫,預設了 self。例如 puts 就是 self.puts 的意思。

Page 20: Ruby 入門 第一次就上手

更多字串函式

var1 = 'stop'var2 = 'foobar'var3 = "aAbBcC"

puts var1.reverse # 'pots'puts var2.length # 6puts var3.upcaseputs var3.downcase

Page 21: Ruby 入門 第一次就上手

流程控制 Flow Control

Page 22: Ruby 入門 第一次就上手

比較函式

puts 1 > 2puts 1 < 2puts 5 >= 5puts 5 <= 4puts 1 == 1puts 2 != 1

puts ( 2 > 1 ) && ( 2 > 3 ) # andputs ( 2 > 1 ) || ( 2 > 3 ) # or

Page 23: Ruby 入門 第一次就上手

真或假只有 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

Page 24: Ruby 入門 第一次就上手

條件分支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

Page 25: Ruby 入門 第一次就上手

控制結構 Case

case name when "John" puts "Howdy John!" when "Ryan" puts "Whatz up Ryan!" else puts "Hi #{name}!"end

Page 26: Ruby 入門 第一次就上手

迴圈

command = ''

while command != 'bye' puts command command = gets.chompend

puts 'Come again soon!'

Page 27: Ruby 入門 第一次就上手

陣列 Array

a = [ 1, "cat", 3.14 ]

puts a[0] # 輸出 1puts a[1] # 輸出 “cat”puts a.size # 輸出 3

Page 28: Ruby 入門 第一次就上手

更多陣列函式

colors = ["red", "blue"]

colors.push("black")colors << "white"puts colors.join(", ") # red, blue, black, white

colors.popputs colors.last #black

Page 29: Ruby 入門 第一次就上手

走訪迴圈 each method

languages = ['Ruby', 'Javascript', 'Perl']

languages.each do |lang| puts 'I love ' + lang + '!'end

# I Love Ruby# I Love Javascript# I Love Perl

Page 30: Ruby 入門 第一次就上手

迭代器 iterator

• 不同於 while 迴圈用法,each 是一個陣列的函式,走訪其中的元素,我們稱作迭代器(iterator)

• 其中 do .... end 是 each 函式的參數,稱作匿名函式( code block)

Page 31: Ruby 入門 第一次就上手

最簡單的迭代器

3.times do puts 'Good Job!'end

# Good Job!# Good Job!# Good Job!

Page 32: Ruby 入門 第一次就上手

code block一種匿名函式,或稱作 closure

{ puts "Hello" } # 這是一個 block

do puts "Blah" # 這也是一個 block puts "Blah"end

Page 33: Ruby 入門 第一次就上手

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]

Page 34: Ruby 入門 第一次就上手

code block僅執行一次呼叫

file = File.new("testfile", "r")# ...處理檔案file.close

File.open("testfile", "r") do |file| # ...處理檔案end# 檔案自動關閉

Page 35: Ruby 入門 第一次就上手

雜湊 Hash(Associative Array)

config = { "foo" => 123, "bar" => 456 }

puts config["foo"] # 輸出 123

Page 36: Ruby 入門 第一次就上手

字串符號 Symbols唯一且不會變動的識別名稱

config = { :foo => 123, :bar => 456 }

puts config[:foo] # 輸出 123

Page 37: Ruby 入門 第一次就上手

定義函式 Methodsdef 開頭 end 結尾

def say_hello(name) result = "Hi, " + name return resultend

puts say_hello('ihower')# 輸出 Hi, ihower

Page 38: Ruby 入門 第一次就上手

定義函式 Methodsdef 開頭 end 結尾

def say_hello(name) result = "Hi, " + name return resultend

puts say_hello('ihower')# 輸出 Hi, ihower

字串相加

Page 39: Ruby 入門 第一次就上手

類別與物件類別 Class

屬性Attributes

函式Methods

物件 Object

屬性Attributes

函式Methods

物件 Object

屬性Attributes

函式Methods

Person

john = Person.new mary = Person.new

Page 40: Ruby 入門 第一次就上手

類別 Classes大寫開頭,使用 new 可以建立出物件

color_string = String.new color_string = "" # 等同

color_array = Array.newcolor_array = [] # 等同

color_hash = Hash.newcolor_hash = {} # 等同

time = Time.newputs time

Page 41: Ruby 入門 第一次就上手

建立自己的類別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

Page 42: Ruby 入門 第一次就上手

建立自己的類別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

建構式

Page 43: Ruby 入門 第一次就上手

建立自己的類別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

建構式

物件變數

Page 44: Ruby 入門 第一次就上手

建立自己的類別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

建構式

物件變數

字串相加(內插法)

Page 45: Ruby 入門 第一次就上手

類別函式

class Greeter

@@name = “ihower” def self.say puts @@name end end

Greeter.say # 輸出 Hello, ihower

Page 46: Ruby 入門 第一次就上手

類別函式

class Greeter

@@name = “ihower” def self.say puts @@name end end

Greeter.say # 輸出 Hello, ihower

類別變數

Page 47: Ruby 入門 第一次就上手

類別函式

class Greeter

@@name = “ihower” def self.say puts @@name end end

Greeter.say # 輸出 Hello, ihower

類別變數

類別函式

Page 48: Ruby 入門 第一次就上手

建立物件變數的存取函式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

等同於

Page 49: Ruby 入門 第一次就上手

Part2: 應用練習gem install sinatra -y --no-ri --no-rdoc

gem install nokogiri -y --no-ri --no-rdoc

Page 50: Ruby 入門 第一次就上手

RubyGems

• Ruby 的套件管理工具

• gem list 可以顯示目前安裝的套件

• 更多套件 http://gemcutter.org/

Page 51: Ruby 入門 第一次就上手

Sinatra

• 一套非常輕量的 web development 工具

• http://www.sinatrarb.com/

• gem install sinatra

Page 52: Ruby 入門 第一次就上手

第一隻 web app執行 ruby myapp.rb,然後打開瀏覽器 http://localhost:4567

# myapp.rbrequire 'rubygems'require 'sinatra'

get '/' do 'Hello world!'end

Page 53: Ruby 入門 第一次就上手

傳遞 URL 參數

require 'rubygems'require 'sinatra'

get '/hello/:name' do # 符合 "GET /hello/foo" 或 "GET /hello/bar" # params[:name] 就會是 'foo' 或 'bar' "Hello #{params[:name]}!"end

Page 54: Ruby 入門 第一次就上手

使用 template建立 views 目錄,加入 hello.erb 檔案

# myapp.rbrequire 'rubygems'require 'sinatra'

get '/hello/:name' do erb :helloend

Page 55: Ruby 入門 第一次就上手

ERB (Ruby Template)<!DOCTYPE html><html><head> <title>Sinatra app</title></head><body> <% 10.times do %> <p><%= "Hello #{params[:name]}!" %></p> <% end %> </body></html>

Page 56: Ruby 入門 第一次就上手

傳遞變數到 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 %>

Page 57: Ruby 入門 第一次就上手

表單製作

# 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

Page 58: Ruby 入門 第一次就上手

nokogiri

• HTML, XML, SAX 解析工具 (parser)

• 使用 XPath 或 CSS 選取想要的資料

• gem install nokogiri

Page 59: Ruby 入門 第一次就上手

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

Page 60: Ruby 入門 第一次就上手

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

Page 61: Ruby 入門 第一次就上手

<!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>

Page 62: Ruby 入門 第一次就上手

Thank you.

參考資料:Learn to Program http://pine.fm/LearnToProgram/Beginning Ruby 2nd. (Apress)