Ruby語言入門

來源:互聯網
上載者:User

一、方法

Ruby 的方法定義允許為參數設定預設值,不過在帶有預設值的參數後面不能出現不帶有預設值的參數(允許 * 和 &),也就是說下面的方法定義是不被允許的,解釋時會出現 parse error。 還有一點與 C# 不同的是,方法定義不能出現在方法調用的後面。

# parse error
def Display(args1="proshea", args2)
end
# 允許
def Display(args1="proshea", *args2)
end
# 允許
def Display(args1="proshea", &args)
end
Show()
# 出現在 Show 調用之後是錯誤的
def Show
end

Ruby 也支援 C# params 這樣的參數功能, 只是 Ruby 用 * 標識罷了。

def Display(*args)
print %Q~#{args.join("-")}~
end
# proshea-32-WinForm
Display("proshea", 32, "WinForm")

同樣的, Ruby 也有類似於 C# delegate 的應用,只是更簡單,直接用 & 來表示,並且 Ruby 用一個稱為 yield 的關鍵字來知會解譯器執行傳入的代碼塊或者說 Proc object(過程對象?)。

1def Display(&block)
2 if block_given?
3 yield(block)
4 else
5 print %Q~沒有傳入過程對象~
6 end
7end
8
9def Show()
10 print %Q~Show 方法調用~
11end
12
13# 沒有傳入過程對象
14Display()
15# 在 Display 內部調用 Show 方法
16# 注意起始大括弧仍然只能和方法名在同一行
17Display(){
18 Show()
19}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.