ruby新手报到之Class小例子

呃,,,,这也是从教程上面摘录的,,,,

感觉这个例子虽然简单,,,,但是挺优雅的,,,,

 

class Person
 def initialize( name, age = 18 )
    @name = name
    @age = age
    @motherland = "China"
  end
  
   def talk
     puts "my name is "+@name + ",age is" +  @age.to_s
     if @motherland == "China"
       puts "I am a Chinese"
      else
        puts "I am a foreigner"
      end
    end
    attr_writer:motherland
  end
  
  p1 = Person.new( "Y", 20 )
  p1.talk


 

你可能感兴趣的:(Ruby)