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 talkputs "my name is "+@name+" ,age is "+@age.to_sif @motherland == "China"puts "I am a Chinese"elseputs "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:motherlandclass Student<Person def talkputs "I am a student. my name is "+@name+" ,age is "+@age.to_s end endp3 = Student.new("xiaoshenyang",38) p3.talk p4 = Student.new("Ben") p4.talkRuby動態性
在運行中添加、修改、移除方法
class Persondef talkputs "I am worker"end end p1 = Person.new p1.talkclass Persondef talkputs "I am #@stu"end attr_accessor:stu end p2 = Person.new p2.stu = "Student" p2.talkclass Person undef:talk end p3 = Person.new p3.talk 本文轉自博客園xingoo的博客,原文鏈接:Ruby編程實踐,如需轉載請自行聯系原博主。總結
- 上一篇: 实操《深入浅出React和Redux》第
- 下一篇: 《软件技术基础》实验指导 实验五