1月24日 ruby基础3部分 Numeric, Array已学。

<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"



原文地址:https://www.cnblogs.com/chentianwei/p/8339891.html