Ruby编程实践
命令
- 常量大写
- 类名和模块名首字母大写,驼峰法,MyClass,Person
- 方法名小写,ruby中末尾添加符号特殊含义:destroyMethod!表示这个方法具有破坏性;isPrime?表示返回bool类型
- 变量、参数小写
空格和括号,保证可读性
- ,、;紧跟,后面加空格
- 操作副前后加空格
- 一元操作符不加空格
- [] . :: 前后不加空格
return
ruby最后一行如果是表达式,则自动返回;如果不是,则不返回
注释
- #单行注释
- =begin ... =end 多行注释
继承
attr_writer:val attr_reader:val attr_accessor:val 实现变量的getter setter
class Person
def initialize(name,age=18)
@name = name
@age = age
@motherland = "China"
end # initialize method
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 # talk method
attr_writer:motherland
# attr_reader:motherland
end
p1 = Person.new("zhaosi",40)
p1.talk
p2 = Person.new("songxiaobao")
p2.motherland = "ABC"
p2.talk
# p2.motherland #open attr_reader:motherland
class Student<Person
def talk
puts "I am a student. my name is "+@name+" ,age is "+@age.to_s
end
end
p3 = Student.new("xiaoshenyang",38)
p3.talk
p4 = Student.new("Ben")
p4.talk
Ruby动态性
在运行中添加、修改、移除方法
class Person
def talk
puts "I am worker"
end
end
p1 = Person.new
p1.talk
class Person
def talk
puts "I am #@stu"
end
attr_accessor:stu
end
p2 = Person.new
p2.stu = "Student"
p2.talk
class Person
undef:talk
end
p3 = Person.new
p3.talk