Ruby attr_accessor 使用,Ruby @成员变量 与 临时变量

#Class describ ------rdoc rules
#
= headers
#
this is header content
#
== sub header
#
this is sub header content
#
=== sub sub header
#
this is sub sub header
class Animal

attr_accessor :name
#-------------①

#this is the comment for the 'new' method !

def initialize type
name
= type #-------------②
end

#this is comment for 'shout' method
# Second Line
#* this is sub line 1
#* this is sub line 2

def shout
if name == 'dog'
puts
"wang! wang!"
elsif name
== 'cat'
puts
"miao! miao!"
elsif name
==nil
puts
"nil"
else
puts
"kao!"
end
end

end

dog
= Animal.new "dog"
puts dog.name
dog.shout
dog.name
= "cat"
dog.shout

本程序输出为:

nil

miao! miao!

-----------------

①: 成员变量

②: 临时变量

attr_accessor 表示后面的为类成员,同时为其提供外部访问能力。即相当于为其提供 get;  set;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值