您的位置:首页 > 编程语言 > Ruby

Ruby for Rails 最佳实践Ⅳ

2013-10-08 14:26 441 查看


第二部分 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) # 错误
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: