ruby学习笔记(6)--范围

#简单的应用
print (1..10).to_a,"/n" #12345678910
print (1...10).to_a,"/n"#123456789
digits=1..10
puts digits.include?(5) #true
puts digits.min #1
puts digits.max #10
print digits.reject{|i| i<5},"/n"#5678910

#让自己的类也支持范围
class SustainRange
  include Comparable
  attr :digits
  def initialize(digits)
   @digits=digits
 end
 #阶乘结果
 def Factorial
   result=1
   1.upto(self.digits){|i| result*=i}
   return result
 end
 #比较操作
 def <=>(other)
    self.digits<=>other.digits
  end
  #支持范围必段 succ方法自增1
  def succ
    SustainRange.new(@digits.succ)
  end
end

#生成实例
sustainRanges= SustainRange.new(1)..SustainRange.new(6)
#each列举
sustainRanges.to_a.each{ |sr| print sr.Factorial,' '}#1 2 6 24 120 720
#是否包含元素
puts sustainRanges.include?(SustainRange.new(3)) #true
#是否在范围之类
#===条件范围
puts sustainRanges===SustainRange.new(9) #false
#5的阶乘大于100
puts sustainRanges.reject{|sr| sr.Factorial<100}[0].digits #5



 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值