Ruby学习笔记(二)

来源:互联网 发布:怎么注册阿里云邮箱 编辑:程序博客网 时间:2024/06/04 08:48

Ruby学习笔记




ruby使用方法
the first half of ruby
we are defining, we are creating
例如 blue_crystal=1 , leaf_tender=5


the second half of ruby
putting things in motion
例如 pipe.catch_a_star


总结:1.defining things 2.putting those things into action ruby的使用就是这么简单
补充:whenever you use a method,you will always be given something back,you can ignore it or use it


关于Nil,false和true
nil is without value,it is not zero.zero is a number
例如 plastic_cup=nil 意味着 plastic_cup is empty(这里的plastic_cup在ruby中不是未定义)
false 和 true 和一般的语言的类似,ruby中除了if 能判断外还有unless(在nil和flase时为真)
例如 print "Yes,plastic cup is up again!" if plastic_cup
print "hardly, it is down." unless plastic_cup


其他一些要点
double equals sign is a method
例如 approaching_guy.==(true)


triple equals is a length of velvet rope,checking values much like the double equals, but it is a longer rope and it sags a bit in the middle
例如 
if 1894..1913===year  "Born" ##这里可以看到有范围浮动,不一定是精确的相等
end


Ruby的类定义
require 'endertromb'
class WishMaker
 def initialize
  @energy = rand(6)
  end
  def grant(wish)
if wish.length>10 or wish.include? ''
raise ArgumentError, "Bad wish"
end
   end
end
创建对象 todays_wishes=WishMaker.new


everything in Ruby is an object
这一点很强大
例如 
number=5  print number.next 输出为6
print 5.class 会输出“Integer”表明5是整型类的对象
print WishMaker.new.class 会输出"WishMaker" 




something about writing methods
1.do not be surprised if people pass unexpected objects into your methods. 对传入的错误值进行异常报错
2.it is poor etiquette to change objects your method is given. 使用dup (x=x.dup)进行复制备份
3.the square brackets can be used to lookup parts inside any Array,Hash or String objects.只有这些中提供了[]方法,同时也提供了[]=方法
4.watch for runaway loops. avoid while and until.


Ruby中的继承
class ToastyBear < Object; end 表明ToastyBear继承了Object这个类
在Ruby中,所有的类都是继承Object类,甚至class也是一个Object,可以说when you alter the object,you alter everything in Ruby. 


关于Ruby中object 和 class 以及 module的区别
If Object is the king, the one who has sired every other part of Ruby, then Module is the poor waifish nun, shielding and protecting all her little Ruby townspeople children. (To complete the analogy: Class is the village school teacher and Kernel is the self-important colonel.)


最后插入一部电影,可见这本书的作者是多么牛叉啊







原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 天猫网络机顶盒打不开了怎么办 天猫机顶盒遥控器丢了怎么办 天猫机顶盒没有遥控器怎么办 天猫机顶盒很卡怎么办 天猫机顶盒没遥控器怎么办 天猫机顶盒看不了怎么办 天猫机顶盒变黑白怎么办 天猫精灵丢了怎么办 咪咕盒子没信号怎么办 猫los灯亮了怎么办 网络猫los闪红灯怎么办 台式电脑二级网页打不开.怎么办 光纤猫los红闪怎么办 系统管理员账户密码被更改怎么办 花呗不能使用了怎么办 开通余额宝提示身份验证失败怎么办 蚂蚁花呗刷脸认证老失败怎么办 火狐浏览器登录系统后打不开怎么办 花呗自动扣费怎么办 彪马运动裤买大了怎么办 淘宝卖家认证无法通过怎么办 淘宝开店申请未认证该怎么办 传照片到淘宝看不到照片怎么办 淘宝店铺秒出复核怎么办 钱盾身份认证一直不通过怎么办 淘宝开店一直不让认证通过怎么办 淘宝店铺不卖东西怎么办 企业误进虚空的增值税发票怎么办 唯品会商品有的不支持退换货怎么办 苹果手机和平板电脑共享怎么办 ipad被锁定了停用了怎么办 word文档被锁定不能编辑怎么办 苹果平板id忘了怎么办 ipad有id锁怎么办换主板 ipad刷机后忘记id密码怎么办 网购买东西手机号错了怎么办? 淘宝卖家虚假交易违规怎么办 好朋友问我借身份证开网店怎么办 为什么淘宝点开就跳过打不开怎么办 刹车油进眼睛里怎么办 眼睛被uv灯刺伤怎么办