《20分鐘體驗 Ruby》通過這個例子你能感受ruby
來源:互聯網
上載者:User
1#!/usr/bin/env ruby
2
3class MegaGreeter
4 attr_accessor :names //設定屬性,自動產生兩個方法(name,name=)用來訪問@name的值
//想知道一個類提供了那些方法?類名.instance_methods會告訴你,如果只想知道自己定義的方法加個false參數
5
6 # Create the object
7 def initialize(names = "World") //建構函式
8 @names = names //定義了局部變數@names
9 end
10
11 # Say hi to everybody
12 def say_hi
13 if @names.nil? //判斷@names是否為nil
14 puts "" //輸出
15 elsif @names.respond_to?("each") //判斷@names是否有each方法
16
17 # @names is a list of some kind, iterate!
18 @names.each do |name| //迴圈
19 puts "Hello #{name}!"
20 end
21 else
22 puts "Hello #{@names}!"
23 end
24 end
25
26 # Say bye to everybody
27 def say_bye
28 if @names.nil?
29 puts ""
30 elsif @names.respond_to?("join")
31 # Join the list elements with commas
32 puts "Goodbye #{@names.join(", ")}. Come back soon!"
33 else
34 puts "Goodbye #{@names}. Come back soon!"
35 end
36 end
37
38end
39
40
41if __FILE__ == $0 //__FILE__ 現在啟動並執行指令檔的名字,
$0
是啟動指令碼的名字.
//這允許代碼作為庫調用的時候不運行啟動代碼,
而在作為執行指令碼的時候調用啟動代碼。
42 mg = MegaGreeter.new
43 mg.say_hi
44 mg.say_bye
45
46 # Change name to be "Zeke"
47 mg.names = "Zeke"
48 mg.say_hi
49 mg.say_bye
50
51 # Change the name to an array of names
52 mg.names = ["Albert", "Brenda", "Charles",
53 "Dave", "Englebert"]
54 mg.say_hi
55 mg.say_bye
56
57 # Change to nil
58 mg.names = nil
59 mg.say_hi
60 mg.say_bye
61end