Ruby 塊(Block)與模組(Module)

2021-07-31 00:07:39 字數 1602 閱讀 6993

定義:首先從中文的字面理解到就是一整塊,聯想到編碼我們便能想到這可能是一些**的一整塊構成吧。沒錯!*a ruby block is a way of grouping statements*-- ruby中的塊就是組織多個**句的一種方式。

表示:ruby標準中,對於單行的**塊使用大括號『{}』表示;對於多行的**塊則使用do..end表示。

用法: a. 方法與塊關聯

**塊作為引數傳遞給方法,使用yield關鍵字執行**塊。

def test_method

puts "this is test_method"

yield

puts "this is test_method again"

yield

end

#**塊一般只出現在與方法呼叫相近的地方

test_method

#輸出的結果如下:

knightdemacbook-pro:ruby knight$ ruby test.rb

this

is test_method

this

is block

this

is test_method again

this

is block

b. yield傳入引數的使用
def test_method

puts "this is test_method"

#yield傳入引數

yield("hello ", "world")

puts "this is test_method again"

yield(1, 2)

end

#**塊一般只出現在與方法呼叫相近的地方

test_method

#輸出內容

knightdemacbook-pro:ruby knight$ ruby test.rb

this

is test_method

hello world

this

is test_method again

3

定義:模組是類、方法和常量的集合,類似類但是不像類可以例項化以及繼承等。

用途:模組有2中目的,其一模組作為乙個namespace讓我們定義的方法名字以及常量名字和其他地方的定義不衝突,其二模組彌補了ruby的類不能進行多重繼承功能。

module

test1

defmethod1

endendmodule

test2

defmethod2

endendclass

a include

test1

include

test2

defmethod3

endend#例項化a類

temp = a.new

#物件temp可以使用三種方法

temp.method1

temp.method2

temp.method3

Ruby學習筆記2(方法 塊 模組)

ruby中的方法就是其他語言中的函式,名稱應以小寫開頭,以免被解釋為常量。引數可有可無,可以有預設值也可以沒有。每個方法都有預設的返回值,就是最後乙個語句的值。def test a1 ruby a2 perl puts 程式語言為 puts 程式語言為 endtest c c test要傳入數量可變...

Block塊 Swift閉包介紹與使用

block塊是隨os x v10.6和ios 4.0一同發布並可用的功能 在這個swift2.0都出來了的時候,不用考慮block版本是否可用的問題 其功能類似於c語言的函式。但是與c語言函式不同在於block可以訪問與之在同乙個作用域的變數。1 block塊 swift閉包實體定義 block指標...

Block塊 Swift閉包介紹與使用

block塊是隨os x v10.6和ios 4.0一同發布並可用的功能,其功能類似於c語言的函式。但是與c語言函式不同在於block可以訪問與之在同乙個作用域的變數。1 block塊 swift閉包實體定義 block指標定義 返回值 block名字 引數列 如 int cube int a bl...