讀《programming ruby》筆記 二 Numbers Ranges

Ruby 支持Integer和浮點型數字類型,在Ruby中Integer 可以達到任何長度,只要你的機器還有可用的內存。Integer 分爲 Fixnum 和 Bignum兩種類型,Fixnum 範圍在 -2^30 到2^30-1,比這更大的範圍是Bignum。

puts (2**30).class
puts (2**30-1).class

#output:
#Fixnum
#Bignum

 

 

   當一個Fixnum長度變大到Bignum的長度時對象會自動變換自己的類爲Bignum,相反當Bignum計算結果屬於Fixnum的範圍時也會變換自己的類爲Fixnum。

   下面看看和Integer的一些常用技巧

 

3.times{|i| puts i.to_s}
#output:
# 0
# 1
# 2

  上面的例子使用times方法,表示執行3次{}裏面的代碼,也可以:

3.times{ puts "times"}

#output:
# times
# times
# times

 

   upto 和 downto

   

3.downto(0) { |i| puts i }
#output
# 3
# 2
# 1
# 0

 

  

 

   <=> 和===,<=>是比較兩個數字,比如a<=>b,如果a<b返回-1,等於返回0,大於返回1。===表示屬於關係比如:

 

 

  

puts (1..5) === 3
puts (1..5) === 9

#output:
# true
# false

   上面的代碼說明了 3屬於1到5之間,而9是不屬於1到5之間的,這裏不光是整數類型,3.5也是屬於1..5的:

 

puts (1..5) === 3.5

#output:
# true

 

 

1..5在Ruby中是一個Range類型對象。Range 當然不只是數字,字符串、日期等等都可以是Range:

 

puts ('a'..'e').to_a

#output
# a
# b
# c
# d
# e

  

   1..5表示1到5幷包含5,1...5 不包含5. Range 用在for 循環中

   

for i in 1...5
  puts i
end

#output:
# 1
# 2
# 3
# 4
 

   (1..5) === 3也可以這樣寫

 

 

 

range = 1..5
puts range.include?(3)

#output:
# true

 

使用Range的step方法打印1到10中的單數,下面表示每隔兩個數字(包含第二個數字)打印一次

 

   

 

  

range = 1..10
range.step(2){|i| puts i}

#output:
# 1
# 3
# 5
# 7
# 9

 

下面讓我們新建一個WeekDays來看看如何定義一個支持Range的類

class WeekDays
  DAYNAME ={'monday'=>1,'tuesday'=>2,'wednesday'=>3,
'thursday'=>4,'friday'=>5,'saturday'=>6,'sunday'=>7}
  attr_accessor :day
  
  
  def initialize(day) 
    @day = day.downcase
  end
  
  # Support for ranges
  def <=>(other)
    DAYNAME[@day] <=> DAYNAME[other.day]
  end
  
  def succ
    raise(IndexError, "Value is wrong") unless DAYNAME.has_key?(@day)
    WeekDays.new(DAYNAME.index(DAYNAME[@day].succ))
  end
end

 for  weekday in WeekDays.new('Monday')..WeekDays.new('Sunday')
   puts weekday.day
 end


#output:
# monday
# tuesday
# wednesday
# thrusday
# friday
# saturday
# sunday
 

 

發佈了10 篇原創文章 · 獲贊 0 · 訪問量 1988
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章