第二部分 Ruby 構造塊
第四章 對象和變量
一、對象
1. 建立類的執行個體——對象
obj = Object.new
2. 定義對象方法
def obj.talk
puts "I am an object."
puts "(Do you object?)"
end
3. 給對象發送消息
object.message
4. 接受參數的方法
def obj.c2f(c)
c * 9 / 5 + 32
end
# puts obj.c2f(100)
5. 方法的傳回值,通常不需要 return(該關鍵字是可選的)
def obj.c2f(c)
return c * 9 / 5 + 32
end
二、對象固有行為
1. 列出對象的固有方法清單:
p Object.new.methods.sort
["==", "===", "=~", "__id__", "__send__", "class",
"clone", "display", "dup", "eql?", "equal?", "extend",
"freeze", "frozen?", "hash", "id", "inspect",
"instance_", "instance_of?", "instance_variable_get",
"instance_variable_set", "instance_variables", "is_a?",
"kind_of?", "method", "methods", "nil?", "object_id",
"private_methods", "protected_methods", "public_methods",
"respond_to?", "send", "singleton_methods", "taint",
"tainted?", "to_a", "to_s", "type", "untaint"]
2. 用 object_id 方法唯一辨別對象
(1)兩個變量引用同一對象 object_id 相同
a = Object.new
b = a
puts "a's id is #{a.object_id} and b's id is #{b.object_id}."
(2)兩個值相同的字元串對象 object_id 不相同
string_1 = "Hello"
string_2 = "Hello"
puts "string_1's id is #{string_1.object_id}."
puts "string_2's id is #{string_2.object_id}."
3. 用 respond_to? 方法查詢對象是否擁有該方法
obj = Object.new
obj.talk
Ruby 會告訴你:
undefined method 'talk' for #<Object:0x401aa18c> (NoMethodError)
使用respond_to?方法可以事先判定對象是否能響應給定的消息。respond_to?常常與條件(if)邏輯一起出現
obj = Object.new
if obj.respond_to?("talk")
obj.talk
else
puts "Sorry, the object doesn't understand the 'talk' message."
end
4. 用 send 方法給對象發送消息
if ticket.respond_to?(request)
puts ticket.send(request)
else
puts "No such information available"
end
5. 必需參數、可選參數以及預設值參數
(1)必需參數
def obj.one_arg(x)
end
obj.one_arg(1,2,3)
結果是:
ArgumentError: wrong number of arguments (3 for 1)
(2)可選參數
def obj.multi_args(*x)
end
(3)混合使用必需參數和可選參數
def two_or_more(a,b,*c)
(5)參數的預設值
def default_args(a,b,c=1)
puts "Values of variables: ",a,b,c
end
(6)參數的順序
def opt_args(a,b,*x) # 正确
def opt_args(a,*x,b) # 錯誤