nd=(value)
return @motherland =value
end
attr_ reader :motherland 相当于
def motherland
return @motherland
end
attr_accessor :motherland 相当于attr_reader:motherland; attr_writer :motherland
八 代码书写规范
a=5
b=3
puts a>b ? "a>b" : "a<=b" # a>b
puts (a>b)? ("a>b") : ("a<=b") # a>b
#puts a>b? "a>b" : "a<=b" 错误语句
九 面向对象(重写 重载)
1.Ruby语言,只有重写,没有其它语言具有的严格意义上的重载
2.Ruby还支持可变参数,我们看程序 E6.1-2.rb :
def sum( *num )
numSum = 0
num.each { |i| numSum+=i }
return numSum
end
puts sum() #0
puts sum(3,6) #9
puts sum(1,2,3,4,5,6,7,8,9) #45
十 实例变量、类变量、类方法
class StudentClass
@@count=0
def initialize
@@count+=1
end
def StudentClass.student_count
puts "This class have #@@count students."
end
end
p1=StudentClass.new
p2=StudentClass.new
StudentClass.student_count # This class have 2 students.
p3=StudentClass.new
p4=StudentClass.new
StudentClass.student_count # This class have 2 students.
十一 单例方法
class Person
def talk
puts "Hi! "
end
end
p1=Person.new
p2=Person.new
def p2.talk #定义单例方法p2.talk
puts "Here is p2. "
end
def p2.laugh #定义单例方法p2. laugh
puts "ha,ha,ha... "
end
p1.talk # Hello!
p2.talk # Here is p2.
p2.laugh # ha,ha,ha...
单例方法也叫作单件方法。定义单例方法,首先要生成一个实例对象,其次,要在方法名前加上对象名和一个点号“.”
十二 模块
Math 模块提供了许多方法,比如:求平方根 sqrt ,使用的时候要这么写:模块名.方法名(参数)
你可以 Math.sqrt(37.2/3) ,Math.sqrt( a*5+b )
Math 模块还提供了两个常量,圆周率π 和自然对数底 e,使用的时候要这么写:模块名::常量名。
定义模块用module...end 。模块与类非常相似,但是:
A) 模块不可以有实例对象;
B) 模块不可以有子类。
十三 糅和(Mix-in) 与多重继承
1.我们有一个Student类,有着Person类的属性和方法,还会做数学题——求平方根。已经有了Me模块,只要Mix-in 在Student类里就可以了。
看程序
module Me
def sqrt(num, rx=1, e=1e-10)
num*=1.0
(num - rx*rx).abs <e ? rx : sqrt(num, (num/rx + rx)/2, e)
end
end
puts "I'm talking."
end
end
class Student < Person
include Me
end
aStudent=Student.new
aStudent.talk # I'm talking.
puts aStudent.sqrt(20.7,3.3) # 4.54972526643248
2.include 方法相对应的,还有一个 extend 方法。如果并不是Student类的每个对象都会求平方根,只有某一个学生会,如何办到呢?
module Me
def sqrt(num, rx=1, e=1e-10)
num*=1.0
(num - rx*rx).abs <e ? rx : sqrt(num, (num/rx + rx)/2, e)
end
end
class Student
end
aStudent=Student.new
aStudent.extend(Me)
puts aStudent.sqrt(93.1, 25)&