当前位置: 代码迷 >> 综合 >> Ruby attr
  详细解决方案

Ruby attr

热度:83   发布时间:2023-12-09 08:53:33.0


实例:

class Animal



 attr_accessor :name    #-------------①成员变量,可以为其提供外部访问能力


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


 def initialize type
   #@name = 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
nil
miao! miao!
  相关解决方案