在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
class Person #initialize是初始化方法,相当于Java的构造器。参数age有一个缺省值18, #可以在任何方法内使用缺省参数,而不仅仅是initialize。如果有缺省参数,参数表必须以有缺省值的参数结束 def initialize( name, age=18 ) @name = name @age = age @motherland = "China" end #初始化方法结束 def talk puts "my name is "+@name+", age is "+@age.to_s #@age.to_s:将数@age转换为字符串。 if @motherland == "China" puts "I am a Chinese." else puts "I am a foreigner." end end # talk方法结束 attr_writer :motherland =begin attr_writer :motherland 相当于 def motherland=(value) return @motherland =value end attr_ reader :motherland 相当于 def motherland return @motherland end attr_accessor :motherland 相当于 attr_reader:motherland;attr_writer :motherland =end end # Person类结束 class Student < Person def talk puts "I am a student. my name is "+@name+", age is "+@age.to_s end # talk方法结束 end # Student类结束 p1=Person.new("kaichuan",20) p1.talk #my name is kaichuan, age is 20 I am a Chinese. p2=Person.new("Ben") p2.motherland="ABC" p2.talk #my name is Ben, age is 18 I am a foreigner. p3=Student.new("kaichuan",25) p3.talk #I am a student. my name is kaichuan, age is 25 p4=Student.new("Ben") p4.talk #I am a student. my name is Ben, age is 18 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论