Ruby  Numeric类

Numeric类

 
Numeric ---------> Integer ---------> Fixnum
                                            ---------> Bignum
              --------->  Float
              ---------> Rational
              ---------> Complex        
更新: 2017/06/15   round默认的情况
更新: 2017/10/05   纠正ceil和floor的错误(搞反了)
更新: 2018/8/28 补充to_s, to_i细节, 纠正round的错误描述
         
 Fixnum  普通整数
 Bignum  大整数
   
   
 Rational (有理数)  有理数,以分数形式产生
 Rational(1, 2)    #1/2
   .to_f()    转换为Float
   .numerator()   分子
   .denominator()   分母
   
 Complex (复数)   复数,以实部和虚部形式生成
Complex(1, 12)  #1 + 12i
   .real()    实部
   .imaginary() 虚部
   
 字符  
 123  10进整数    123_123_123 
 0123   8进整数
 0o123   8进整数
 0d123  10进整数
 0x123  16进整数
 0b1111011   2进整数
 123.45   浮动小数点数
 1.23e4  浮动小数点数的指数表达
 1.23e-4  浮动小数点数的指数表达
 123r  有理数  123/1
 123.45r  有理数 123.45/1 = 2469/20
 123i  虚数 123i
 123.45i  虚数 123.45i
   
 运算  + - * / % **(幂运算)
 位运算: 只可用于Integer
 ~, &, |, ^(xor)
 >>, <<
 商  11.div(2) = 5
 商 (有理数形式)  11.que(2) = 11/2
 余数 (恒正)  -1.modulo(2) = 1
 余数 (同符号)  -1.remainder(2) = -1
 商与余数  -1.divmod(2) = [-1, 1]
 Math  使用: Math.func-name
 sin(x)
 cos(x)
 tan(x)
 sqrt(x) 平方根
 cbrt(x) 立方根
   
 类型转换  to_s(base=10)  转文字 默认转化为10进制
 to_i(base=10)  转整数 默认转化为10进制
 to_f()  转浮动小数点数
 round(ndigits=0)  四舍五入n位小数 默认取整
                n可以为负数, 为取整后从小位开始把位上的数变0
                123.123.round(-1) = 120
 ceil()      最小更大整数
                1.6.ceil() = 2
 floor()    最大更小整数
                1.6.floor() = 1
 随机数   r = Random.new()  可以手动添加参数
                              默认随机数参数
 r.rand()                 生成随机数
安全随机数
 require "securerandom"
 SecureRandom.random_bytes(n)
          生成n位的随机字符串
 SecureRandom.base64(n)
          生成n位的随机字符串(0~63的值)
 循环  n.times() do |temp|    进行n次(0...n-1)
    ...
 end
 从n到to  n.upto(to) do |temp|    n..to
    ...
 end
 从to到n,递减  n.downto(from) do |temp|
    ...
 end
 从n到to
 n..to, r = n+t*step
n.step(to, step) do |temp|   
    ...
 end 
 模块  include Comparable
 自定义 <=>
 a > b: 1
 a == b: 0
 a < b: -1
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

 

posted @ 2017-05-19 10:43  懒虫哥哥  阅读(179)  评论(0编辑  收藏  举报