Ruby 簡明教程 Part 5

1.簡介

2.安裝

3.基本語法

4高級進階

 

 

------繼續

3.基本語法

3.10 Modules 模塊

模塊是將方法,類,和常量分門別類的方式。有倆大有點:

  • 模塊提供namespace,防止名字衝突 provide a namespace and prevent name clashes.

  • 模塊實現混合設施(mixin  facility)

模塊定義命名空間,一個沙箱,沙箱中的方法和常量你可以放心使用而不必擔心被其它方法和常量干擾。

格式

module Identifier
   statement1
   statement2
   ...........
end

模塊常量和類常量一樣,開頭用大寫字母。模塊定義類似,模塊方法也和類方法一樣來定義。

 和類方式一樣,通過在模塊方式前置模塊名加點(.)來調用;而引用常量前置模塊名和倆個分號。

 

# Module defined in trig.rb file

module Trig
   PI = 3.141592654
   def Trig.sin(x)
   # ..
   end
   def Trig.cos(x)
   # ..
   end
end

可以定義另外一個同名但不同功能的模塊

# Module defined in moral.rb file

module Moral
   VERY_BAD = 0
   BAD = 1
   def Moral.sin(badness)
   # ...
   end
end

和類方式一樣,在模塊中定義一種方法,指定模塊名,加點,然後是方法名字。

3.10.1  require 語句

require和C/C++的include, Python 的import類似。 

格式

require filename

這兒文件名,不需要帶rb後綴。
$LOAD_PATH << '.'

require 'trig.rb'
require 'moral'

y = Trig.sin(Trig::PI/4)
wrongdoing = Moral.sin(Moral::VERY_BAD)

使用$LOAD_PATH << '.'  來指定當前目錄爲載入目錄,如果你不想使用環境變量 $LOAD_PATH,那麼可以使用require_relative來包含相對目錄。

重要 −不同文件有同樣的函數,這會導致歧義。可以使用模塊名來調用適當的函數,避免歧義。

3.10.2 include 語句

可以在類中嵌入模塊。

格式

include modulename

If a module is defined in a separate file, then it is required to include that file using require statement before embedding module in a class. 如果模塊定義在一個分開的文件中,在嵌入模塊到類之前,需要使用require 語句將那個文件include 進來。

support.rb:

module Week
   FIRST_DAY = "Sunday"
   def Week.weeks_in_month
      puts "You have four weeks in a month"
   end
   def Week.weeks_in_year
      puts "You have 52 weeks in a year"
   end
end

現在,可以將此模塊include到類中:demo_include.rb

#!/usr/bin/ruby
$LOAD_PATH << '.'
require "support"

class Decade
include Week
   no_of_yrs = 10
   def no_of_months
      puts Week::FIRST_DAY
      number = 10*12
      puts number
   end
end
d1 = Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year
d1.no_of_months

運行結果:

zzl@zzl-VirtualBox:~/rubyprojects$ ruby demo_include.rb
Sunday
You have four weeks in a month
You have 52 weeks in a year
Sunday
120

3.10.3  Mixins 混合

 

類可以多重繼承。

Ruby 不直接支持多重繼承,但是Ruby 模塊提供了稱做混合Mixin的設施。 

Mixins 提供向類添加功能的美妙控制方式,不過mixin的真正威力它的代碼可以與它使用的類的代碼交互。

檢查以下示例代碼:demo_mixin.rb

module A
   def a1
      puts "method a1 in module A"
   end
   def a2
      puts "method a2 in module A"
   end
end
module B
   def b1
      puts "method b1 in module B"
   end
   def b2
     puts "method b2 in module B"
   end
end

class Sample
include A
include B
   def s1
     puts "method s1 in class Sample"
   end
end

samp = Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1

執行結果:
zzl@zzl-VirtualBox:~/rubyprojects$ ruby demo_mixin.rb
method a1 in module A
method a2 in module A
method b1 in module B
method b2 in module B
method s1 in class Sample

模塊 A 包含 a1,a2倆個方法. 模塊 B 有b1,b2方法. Sample 類 include 模塊A 和模塊B。Sample 類可以訪問 所有四個方法, 即y, a1, a2, b1, and b2.  這樣,你可以說Sample類有多重繼承或混合mixin。

3.11  string 字符串

字符串對象存儲和操作任意序列的單字節或多字節,典型的是人類語言。

單引號來定義字符串 (‘’).

'This is a simple Ruby string literal'

如果單引號要在字符串中,則需要轉義符\’. 例如:

'Won\'t you read O\'Reilly\'s book?'

3.11.1Expression Substitution 表達式替換

表達式替換是將Ruby 表示式值使用#{}來嵌入的方式。

 

#!/usr/bin/ruby
x, y, z = 12, 36, 72
puts "The value of x is #{ x }."
puts "The sum of x and y is #{ x + y }."
puts "The average was #{ (x + y + z)/3 }."

結果:

The value of x is 12.
The sum of x and y is 48.
The average was 40.

3.11.2 General Delimited Strings 通用分割字符串

With general delimited strings, 使用通用分割的字符串,可以在一對匹配的任意分隔符中創建字符串。分隔符,例如 : !, (, {, < 等, 前置字符 (%). Q, q, a和 x 有特殊的意義。

%{Ruby is fun.}  等同於 "Ruby is fun."
%Q{ Ruby is fun. } 等同於 " Ruby is fun. "
%q[Ruby is fun.]  等同於單引號字符串 
%x!ls! 等同於  `ls`

3.11.3 Escape 逃逸字符

下表是逃逸或不可打印字符,可以用\來表示。

 

Character Encoding 字符編碼

 Ruby 默認是 ASCII碼,可以用單字節表示。 UTF-8,  是另外一種現代字符集,可以用1到4個字節表示。

你可以用變量 $KCODE 在程序開頭定義字符集:

$KCODE = 'u'

 

3.11.4 String Built-in Methods 字符串內置方法

調用字符串方法需要字符串對象實例。以下方式創建字符串對象實例:

new [String.new(str = "")]

 這將返回一個新的字符串對象,它有參數str的副本。然後,可以使用任何可用的實例方法。

#!/usr/bin/ruby

myStr = String.new("THIS IS TEST")
foo = myStr.downcase

puts "#{foo}"

執行結果:

this is test

 

3.11.5 String unpack Directives 字符串解包指令

 

舉例:

"abc \0\0abc \0\0".unpack('A6Z6') #=> ["abc", "abc "]
"abc \0\0".unpack('a3a3') #=> ["abc", " \000\000"]
"abc \0abc \0".unpack('Z*Z*') #=> ["abc ", "abc "]
"aa".unpack('b8B8') #=> ["10000110", "01100001"]
"aaa".unpack('h2H2c') #=> ["16", "61", 97]
"\xfe\xff\xfe\xff".unpack('sS') #=> [-2, 65534]
"now = 20is".unpack('M*') #=> ["now is"]
"whole".unpack('xax2aX2aX1aX2a') #=> ["h", "e", "l", "l", "o"]

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章