Ruby学习笔记(二)

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.)


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







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值