Ruby學習筆記(二)

來源:互聯網
上載者:User

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

最後插入一部電影,可見這本書的作者是多麼牛叉啊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.