前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Ruby编程实践

Ruby编程实践

作者头像
用户1154259
发布2018-01-17 16:03:35
6080
发布2018-01-17 16:03:35
举报

命令

  • 常量大写
  • 类名和模块名首字母大写,驼峰法,MyClass,Person
  • 方法名小写,ruby中末尾添加符号特殊含义:destroyMethod!表示这个方法具有破坏性;isPrime?表示返回bool类型
  • 变量、参数小写

空格和括号,保证可读性

  • ,、;紧跟,后面加空格
  • 操作副前后加空格
  • 一元操作符不加空格
  • [] . :: 前后不加空格

return

ruby最后一行如果是表达式,则自动返回;如果不是,则不返回

注释

  • #单行注释
  • =begin ... =end 多行注释

继承

attr_writer:val attr_reader:val attr_accessor:val 实现变量的getter setter

代码语言:javascript
复制
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动态性

在运行中添加、修改、移除方法

代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-10-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 命令
  • 空格和括号,保证可读性
  • return
  • 注释
  • 继承
  • Ruby动态性
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档