<div style="background:lightblue">

第12章 数值类

12.1 数值的构成

Numeric-> Integer-> Fixnum,Bignum(非常大的整数)

-> Float

-> Rational (rational thoughts, decisions etc are based on reasons rather than emotions)

无限不循环小数以外的数(整数,分数)

-> Complex复数

> a = Rational(2, 5)   

#=> Rational(分子,分母) 分子:numerator,分母:denominator

 => (2/5)
> b = Rational(1,3)
 => (1/3)
> p [a,b]
 => [(2/5), (1/3)]
> c = a + b
 => (11/15)
> p c
 => (11/15)
> p c.to_f
 => 0.7333333333333333
> p [c.numerator, c.denominator]
 => [11, 15]

Complex对象用"Complex(实数,虚数)"的形式定义 .Complex(real, imaginary)

12.2数值的字面量

0b1111011 #=>二进制整数123

123.45 浮点小数

1.23e4     #=> 12300

1.23e-4   #=>  0.000123

123_123   #=> 123123  下划线会被忽略,这样写看起来很舒服,用起来方便

123r         #=> 有理数(123/1)

123i         #=>  虚数的123i

12.3算数运算

% 取余运算, **乘方运算

整数和浮点数运算的结果是浮点数。

整数除以有理数的结果是有理数。

> r = (2/5r) + (1/3r)   #=> (11/15)

> p r   #=> (11/15)

除法:

x.div(y)    返回x除以y以后的商的整数

x.quo(y)    返回x除以y以后的商

x.remainder(y)  返回余数,结果的符号和x一样

x.modulo(y)    #=>   %

12.4 Math模块

提供了三角函数,对数函数等常用的函数运算法,和2个常量PI ,E

12.5数值类型转换

> 10.to_f

 => 10.0
> 10.8.to_i
 => 10
> 10.8.round(1)
 => 10.8 保留小数,多的小数位四舍五入
> "123.3".to_f
 => 123.3
> 10.8.ceil 取ceil天花板
 => 11
> 10.8.floor 取floor地板
 => 10
> 1.5.to_r
 => (3/2)
> 1.5.to_c
 => (1.5+0i)

12.6 位运算

对以二进制表现的整数的每个二进制位进行的操作和运算。

bit(binary digit) 0或1,计算机中的最小数据单位。

1个字节有8bit. 1个字节可以表示十进制数0-255.十六进制00到FF

12.7随机数

  • 没有规程和法制依据
  • 一定范围内的数会均等的出现

Random.rand 得到随机数。

rand(100)  #=> (0..100)指定正参数后返回0至正整数之间的数值0至99

属于伪随机数,是用算法生成的看起来相似随机数。但需要以某个值为基础,这个值叫做种子。

因此如果种子一样,得到的值也可能重复。

Random.new

随机生成一个种子。例子:

> r = Random.new

 => #<Random:0x007fd4411551b8>
> r.rand   这样可以模仿出真随机。先生成随机种子,再用这个种子背后的算法生成随机数。
 => 0.4741092108991146
> r.rand
 => 0.7211008876430876

Ruby 有个securerandom库,用于信息安全领域用到的随机数字。

12.8 计数

n.times{|i| ...}

from.upto(to){|i|...}

from.downto(to){|i|...}

from.step(to, step){|i|...}

step(by: step, to: limit) {|i| block } → self

ary = 2.step(10).collect{|i| i*2 }

=> [4, 6, 8, 10, 12, 14, 16, 18, 20]

  

12.9 近似值误差。

浮点数的误差,原因:二进制无法正确的表示1/5, 1/3之类的无限数,会在适当位置截断,这样就产生了误差。

可以用Rational进行类似运算。

> a = 1/10r + 2/10r
 => (3/10)
> b = 3/10r
 => (3/10)
> p [a,b]
 => [(3/10), (3/10)]
> a == b
 => true

Comparable 模块

比较运算符也是方法,这个模块封装了比较运算符, 将其Mix-in到类后,就可以实现对实例进行比较的方法。

Numeric, String, Time都包含了Comparable模块。



13 Array

https://ruby-doc.org/core-2.5.0/Array.html#method-i-delete

13.2 创建

> a = Array.new
 => []
> b = Array.new(5)
 => [nil, nil, nil, nil, nil]
> c = Array.new(5, "hello")
 => ["hello", "hello", "hello", "hello", "hello"] 

Array.new(长度,初始值) #=>new(size=0, default=nil) 可以用于创建value相同的数组。

new(array)  #复制一个新数组。两者无关系

另外如果是以下写法则仅仅加个标签:

⚠️ 其中的区别:

> a1 = [1,2,3]
 => [1, 2, 3]
> a2 = a1     仅仅增加一个标签,还是指向同一块内存
 => [1, 2, 3]
> a1.equal? a2
 => true

new(size) {|index| block }  #根据index索引,来创建每个值value.例子:

> d = Array.new(3){|index| "aa"}
 => ["aa", "aa", "aa"]
> Array.new(3){ |index| index ** 2 }
 => [0, 1, 4]

13.22 %w  %i

%w:创建不包含空白的字符串数组

> word = %w(Ruby Per1 Python Scheme Pike)

=> ["Ruby", "Per1", "Python", "Scheme", "Pike"]

%i : 创建元素符号数组

index = %i(Ruby Per1 Python Scheme)

=> [:Ruby, :Per1, :Python, :Scheme]

13.23  to_a方法,每个k-v对儿都成为一个数组,统一放到一个大数组中。

> color_table = {black: "#00000", :white => "#fffffff"}
 => {:black=>"#00000", :white=>"#fffffff"}
> color_table.to_a
 => [[:black, "#00000"], [:white, "#fffffff"]]

13.24 使用String的split method

> column = "2018/2/1, foo.html, proxy.rb".split(",")

=> ["2018/2/1", " foo.html", " proxy.rb"]


13.3  index的使用方法

13.31 获得element

  1. a[n]
  2. a[n..m] 或者a[n...m]
  3. a[start, length]
等价
ary[index]                       slice(index) → obj or nil ary.at(index)

ary[start, length]         slice(start, length) → new_ary or nil
ary[range]                       slice(range) → new_ary or nil
> alpha = "a b c d e f g".split(" ")
 => ["a", "b", "c", "d", "e", "f", "g"]
> bb = alpha[1..3]
 => ["b", "c", "d"]
> bb = alpha[1...3]
 => ["b", "c"]
> cc = alpha[1..10]
 => ["b", "c", "d", "e", "f", "g"]
> dd = alpha[2, 3]

=> ["c", "d", "e"]

13.32 (批量)替换element

a[index] = item

批量替换,可以使用上节的方法。 如 a[n..m] = []

> alpha

 => ["a", "b", "c", "d", "e", "f", "g"]
> alpha[2..4] = ["C", "D", "E"]
 => ["C", "D", "E"]
> alpha
 => ["a", "b", "C", "D", "E", "f", "g"]

13.33 插入元素,(替换0个元素)

a[n, 0]  #在n前面插入元素。

> alpha = ["a","b","c"]
 => ["a", "b", "c"]
> alpha[2,0] = [1,2]
 => [1, 2]
> alpha
 => ["a", "b", 1, 2, "c"]

13.34 values_at(n1, n2...) -> new_ary  通过index获得想要的element

> a = %w(a b c d e f)
 => ["a", "b", "c", "d", "e", "f"]
> a.values_at(1, 3, 6)
 => ["b", "d", nil]
> a.values_at(1, 3, 4)
 => ["b", "d", "e"]

13.4 作为集合的数组

ary = ary1 & ary2 交集

ary = ary1 | ary2 并集

ary = ary1 - ary2 差运算

例子:

>   ary1 = ["a", "b", "c"]
 => ["a", "b", "c"]
> ary2 = ["b", "c", "d"]
 => ["b", "c", "d"]
> ary1 - ary2
 => ["a"]

| 和 + 的区别:

| 两个数组最后只保留唯一的元素,+ 后面的数组附加到前面的数组后 。

> ary1 = [1,2,2,3]
 => [1, 2, 2, 3]
2.3.1 :044 > ary2 = [2,3,4,5]
 => [2, 3, 4, 5]
2.3.1 :045 > ary1 | ary2
 => [1, 2, 3, 4, 5]
2.3.1 :046 > ary1 + ary2
 => [1, 2, 2, 3, 2, 3, 4, 5]

13.5 作为列的Array

push 和 << 类似,都是 添加到最后。

shift 删除第一个,pop删除最后一个

unshift 添加到第一个,。

> alpha = %w(a b c d e)
 => ["a", "b", "c", "d", "e"]
> alpha.push("f")

=> ["a", "b", "c", "d", "e", "f"]

> alpha.shift   => "a"

> alpha   => ["b", "c", "d", "e", "f"]

 > alpha = %w(a b c d e)
 => ["a", "b", "c", "d", "e"]
> alpha.pop       => "e"
> alpha     => ["a", "b", "c", "d"]

13.6 Array 的 主要method

13.61 add element

  1. unshift(obj,...) -> ary
  2. ary << obj → ary
  3. push(obj, ... ) → ary   等同于<<  ,但可以放多个object
  4. a.concat(b) -> ary     concatenate:to link or join together, esp in a chain or series (数组和字符串都有的方法) concat(other_ary1, other_ary2,...)-> ary (ruby,2.5版本的新增功能)
  5. ary + other_ary → new_ary
  6. a[n] = item;   修改
  7. a[n..m] = item;  范围修改
  8. a[n, length] = item;  如果length等于0,相当于在n,前面插入item.
> a = [1,2,3,4,5]
> a[1, 2] = "aa"
> a  => [1, "aa", 4, 5]
> a[1, 0] = "bb"
> a
 => [1,  "bb",  "aa",  4, 5]

Freeze方法

> a = [1,2,3]      => [1, 2, 3]

> a.freeze
> b = a    
> b.pop    #因为a被冻结,所以不能修改
RuntimeError: can't modify frozen Array
from (irb):63:in `pop'
from (irb):63
from /Users/chentianwei/.rvm/rubies/ruby-2.3.1/bin/irb:11:in `<main>'
2.3.1 :065 > c = a.dup    #建立一个副本,注意和 ⚠️  clone的区别。
 => [1, 2, 3]

dup和clone的区别:

While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance.  When using dup, any modules that the object has been extended with will not be copied.

13.62 从数组中删除元素

a.compact  -> new_ary

Returns a copy of self with all nil elements removed.

a.compact! ->ary or nil

compact:(vt)to press sth together so that it becomes smaller or more solid.

delete:根据元素删除

a.delete(obj) -> item or nil

a.delete(obj){block} -> item or result of block(false/nil的话返回block)

Deletes all items from self that are equal to obj.If the optional code block is given, the result of the block is returned if the item is not found.

delete_at: 根据索引删除a.delete_at(index) -> obj or nil

delete_if / reject! / reject :用循环进行条件选删

a.delete_if{|item| block } -> ary

Delete every element of self for which block evaluates to true, 每次删除立即生效。而不是等循环迭代 iteration is over结束后再一起生效。

类似于:

a.reject! {|item| block } → ary or nil

reject {|item| block } → new_ary

slice

a.slice!(n)

a.slice!(n..m)

a.slice!(n, len)

根据index,删除a的指定部分,并返回删除部分的值。

uniq!

a.uniq -> new_ary

a.uniq{|item| ...}  -> new_ary

a.uniq! -> ary

a.shift  and a.pop

13.63 替换数组

collect, map:循环遍历

collect { |item| block } → new_ary

#把每次块的最后一行代码的结果集合成数组,然后return

collect等同于map,

collect!{|item| block } -> ary

fill

a.fill(value) ->ary

a.fill(value, begin [,length] ) # a[n,len] = item

a.fill(value, n..m)  # a[n..m] = item

a.flatten(level) -> new_ary  #把数组内的嵌套数组去掉,根据level去掉层数。

a.reverse -> new_ary

a.sort  -> new_ary     #二分快速排序法,排序。

a.sort{|a,b| block} -> new_ary

Comparisons for the sort will be done using the <=> operator or using an optional code block.

a.sort_by

13.7  数组和迭代器

数组是object的集合,iterator是循环处理的方法。

接受者为范围对象,而结果为数组对象,迭代器和数组被紧密的结合在一起了。

> a = 1..5
 => 1..5
> b = a.collect{|i| i += 1}
> b
 => [2, 3, 4, 5, 6]

13.8处理Array的element

13.81循环和索引

for i in 0..n

block

end

13.82 each 和 each_with_index

13.83 while  可以用来逐个删除数组元素。

list =[1,2,3,4]

i = 0

while i < list.size

list.pop

i += 1

end

puts list  #=> []

13.9 数组的元素

数组内可以嵌套。

初始化有两种定义:

  1. Array.new(size, default)    #这样每次改一个数,所有内部对象都会改
  2. Array.new(size){|index| block}  # 各个嵌套的块都是独立的。
例子: 

> a = Array.new(3, [0,0,0])

 => [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
> a[0][1] = 2
> a
 => [[0, 2, 0], [0, 2, 0], [0, 2, 0]]
> b = Array.new(3){[0,0,0]}
 => [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
> b[0][1] = 2
> b
 => [[0, 2, 0], [0, 0, 0], [0, 0, 0]]

Enumerable mode

The Enumerable mixin provides collection classes with several traversal and searching methods,and with the ability to sort. The class must provide a method each,which yields successive members of the collection. if Enumerable#max,#min,or #sort is used, the objects in the collection must also implement a meaningful <=> operator,as these methods rely on an ordering between members of the collection.

Public Instance Methods:

all?[{|obj| block}] -> true or false   #反义词  none?

Passes each element of the collection to the given block. The method returns true if the block never returns false or nil.

%w[ant bear cat].all? { |word| word.length >= 3 } #=> true

any?[{|obj| block}] -> true or false

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil.

%w[ant bear cat].any? { |word| word.length >= 4 } #=> true

collect{|obj| block } ->new_array 把各元素的块执行结果以数组的形式返回。

就是对原数组对象进行修改后返回修改后的形式。

count ->int

count(item) ->int #If an argument is given, the number of items in enum that are equal to item are counted.

cycle(n = nil) {|obj| block} -> nil   #根据n参数,决定遍历几遍对象。类似times方法。

Calls block for each element of enum repeatedly n times or forever if none or nil is given.

select {|obj| block } ->array  #等同find_all  省略了if条件判断,反义词reject

Returns an array containing all elements of enum for which the given block return returns a true value.

加!号则是改变自身。

(1..10).find_all { |i|  i % 3 == 0 }   #=> [3, 6, 9]

each_slice(n) {...} -> nil

Iterates the given block for each slice of <n> elements.(英文)

每次把n个元素放到块中执行,直到遍历完所有元素。(我的翻译)

指定参数n,n个元素为一组,把各组元素传给块执行。(教程翻译)

(1..10).each_slice(3) { |a| p a }
=>
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]

find #等同detect

to_a

# 使用范围对象的to_a方法
a = (1..100).to_a

inject(initial=nil){|memo, obj| block } ->obj

例子:

a = (1..10).to_a

a.inject{|sum, n| sum + n} -> 55

If you do not explicitly specify an initial value for memo, then the first element of collection is used as the initial value of memo.
join(separator=$,) → str

[ "a", "b", "c" ].join        #=> "abc"
[ "a", "b", "c" ].join("-") #=> "a-b-c"



p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Arial; color: #3d3d3d; -webkit-text-stroke: #3d3d3d}
span.s1 {font-kerning: none}

1月24日 ruby基础3部分 Numeric, Array已学。的更多相关文章

  1. 1月10日 ruby基础教程,查漏补缺; 2月22日 Exception补充

    https://ruby-doc.org/core-2.5.0/Exception.html 1月20日练习完1,2章. 第一章 初探 ‘’单引号不执行转义符. \t 制表符.\n 换行符. p me ...

  2. 2017年5月24日 HTML 基础知识(二)

    1 快捷方式:html:xt +tab   过渡XHTML html:xs+tab  严格XHTML !+tab  html5的标签结构 2.Charset   编码 <meta charset ...

  3. 36.React基础介绍——2019年12月24日

    2019年12月24日16:47:12 2019年10月25日11:24:29 主要介绍react入门知识. 1.jsx语法介绍 1.1 介绍 jsx语法是一种类似于html标签的语法,它的作用相当于 ...

  4. 北京Uber优步司机奖励政策(4月24日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  5. 北京Uber优步司机奖励政策(3月24日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  6. 北京Uber优步司机奖励政策(2月24日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  7. 北京Uber优步司机奖励政策(1月24日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  8. 北京Uber优步司机奖励政策(12月24日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  9. 如何看待 SAE 在2014 年 3 月 24 日发生的的大面积宕机事故?

    3 月 24 日晚间大约 23 点左右,新浪云 SAE 一处核心机柜掉电,导致 SAE 平台下大量应用无法正常访问,并在 10 小时后才陆续修复.这次事故暴露 SAE 的哪些缺陷?SAE 运维人员又是 ...

随机推荐

  1. python 元组 序列上使用enumerate()函数

    不能直接for n,x,y in enumerate(data)

  2. 左连接LEFT JOIN 连接自己时的查询结果测试

    #左连接LEFT JOIN 连接自己时的查询结果测试 #左连接LEFT JOIN 连接自己时的查询结果(都会出现两个重复字段),两个表都有as后只能查询相等条件merchant_shop_id非nul ...

  3. WireShark学习

    1.打开wireshark->Capture->Interface->选择你的网卡(选中)->Start 2.OK抓包开始,工具栏上有stop,点击停止抓包 3.过滤,这个你可 ...

  4. ui-grid angularjs

    <pre name="code" class="html"><!--ui-grid css--> <link rel=" ...

  5. 如何写出一个让人很难发现的bug?

    程序员的日常三件事:写bug.改bug.背锅.连程序员都自我调侃道,为什么每天都在加班?因为我的眼里常含bug. 那么如何写出一个让(坑)人(王)很(之)难(王)发现的bug呢? - 1 -新手开发+ ...

  6. bzoj1638 / P2883 [USACO07MAR]牛交通Cow Traffic

    P2883 [USACO07MAR]牛交通Cow Traffic 对于每一条边$(u,v)$ 设入度为0的点到$u$有$f[u]$种走法 点$n$到$v$(通过反向边)有$f2[v]$种走法 显然经过 ...

  7. 20145105 《Java程序设计》实验三总结

    实验三 一.       实验内容 结对修改实验一代码,重点学习重构 二.       实验步骤 下载结伴同学的实验一代码 初始代码 进行整数.小数和负数的多组数据测试,发现一个运行错误的例子 分析后 ...

  8. Windows10 蓝屏 DRIVER_IRQL_NOT_LESS_OR_EQUAL (vfilter.sys)的可能解决方法

    早上我的笔记本从休眠中开机的时候突然出现了蓝屏,这个蓝屏在前几天出现过了.两次提示的终止代码都一样.我的笔记本型号是DELL XPS15 9560 我的笔记本配置: 类别 型号 内存 16GB DDR ...

  9. NOIP 华容道

    描述 小 B 最近迷上了华容道,可是他总是要花很长的时间才能完成一次.于是,他想到用编程来完成华容道:给定一种局面,华容道是否根本就无法完成,如果能完成,最少需要多少时间. 小 B 玩的华容道与经典的 ...

  10. 在CentOS Linux系统上,添加新的端口,启用ssh服务

    SSH作为Linux远程连接重要的方式,如何配置安装linux系统的SSH服务,如何开启SSH? SSH是什么? SSH 为 Secure Shell 由 IETF 的网络工作小组(Network W ...