`
java-admin
  • 浏览: 1376435 次
  • 性别: Icon_minigender_1
  • 来自: 陕西.西安
社区版块
存档分类
最新评论

Ruby学习六 数组(3)

 
阅读更多

http://hi.baidu.com/hackerbase/blog/item/c38eb58f0bab71e2f11f3638.html

 

 

小知识:
叹号! 一般用到这个时候,是修改自身
问号? 一般用到这个的时候,时返回布尔
符号[] 代表是数组
符号{} 代表散列
--------------------------------------------------------------------
01.数组的创建和初始化
a = Array.[](1,2,3,4)
b = Array[1,2,3,4]
c = [1,2,3,4]
d = Array.new #创建一个空数组
e = Array.new(3) #[nil,nil,nil] 初始大小3
f = Array.new(3,"xx") #["xx","xx","xx"] 初始大小3 初始值"xx"
f[0].capitalize! #=> ["Xx","Xx","Xx"]
g = Array.new(3){"yy"} #=> ["yy","yy","yy"]
g[0].capitalize! #=>["Yy","yy","yy"]
--------------------------------------------------------------------
02.数组元素的访问和赋值
a = [1,2,3,4,5,6]
b = a[0] #=>1 第1位
c = a.at[0] #=>1 当1位时
d = a[-2] #=>5 倒数第2位
e = a.at[-2] #=>5 当倒数第2位
f = a[9] #=>nil 不存在第9位
g = a.at[9] #=>nil 当第9位不存在
h = a[3,3] #=>[4,5,6] 从第4位开始,一共3个
i = a[2..4] #=>[3,4,5] 第2位后 到第4位之间
j = a[2...4] #=>[3,4] 第2位后 到第4位之前(不包括4位)

a[1] = 8 #=> [1,8,3,4,5,6] 第2位被重新复制
a[1,3] = [10,30,30] #=>  [1,10,30,30,5,6] 从第2为开始替换数组 共3位
a[0..3] = [2,4,6,8] #=> [2,4,6,8,5,6] 从第1位开始到第4位 替换
a[-1] = 12 #=> [2,4,6,8,5,12] 替换最后一位

k = [2,4,6,8,10]
k[1..2] = [3,3,3] #=>[2,3,3,3,8,10] 替换第2位~第三位之间的
k[7] = 99 #=> [2,3,3,3,8,10,nil,99] 第8位增加99 第7位不存在

m = [1,3,5,7,9]
m[2] = [20,30] #=> [1,2,[20,30],7,9] 把第3位替换为此数组

m = [1,3,5,7,9]
m[2..2]=[20,30] #=> [1,2,20,30,7,9] 在第2位之间加入数组

x = [0,2,4,6,8,10,12]
a = x.slice(2) #=>4 取第3位
b = x.slice(2,4) #=>[4,6,8,10] 从第3位开始取 4个数
c = x.slice(2..4) #=>[4,6,8] 从第3位..到第5位
x.first #=>0 取第1位
x.last #=>12 取最后1位

x = [10,20,30,40,50,60]
y = x.values_at(0,1,4) #=>[10,20,50] 值在1位 2位 5位时,分别是什么
z = x.values_at(0..2,5) #=>[10,20,50,60] 值在1位~3位之间,6位分别是什么
--------------------------------------------------------------------
03.确定数组的长度
x = ["a","b","c","d"]
a = x.length #=>4
a = x.size #=>4
y = [1,2,nil,nil,3,4]
c = y.size  #=>6
d = y.length #=>6
e = y.nitems #=>4
--------------------------------------------------------------------
04.数组的比较
a = [1,2,3,9,9]
b = [1,2,4,1,1]
c = a <=> b #=> -1 意思是 a<b 从左到右,依次比较,左侧优先级高

d = [1,2,3]
e = [1,2,3,4]
c = a <=> b #=> -1 意思是 a<b 元素相同,末尾相同,则较长数组更大

定义一个比较方法class Comparable,因为数组默认只有 <=> 现在通过自写class增加 < > <= >=
class Comparable
def <(other)
(self <=>other) == -1
end
def <=(other)
(self < other) or (self == other)
end
def >(other)
(self <=> other) == 1
end
def >=(other)
(self > other) or (self == other)
end
end
然后就可以直接数组 a < b 返回true
--------------------------------------------------------------------
05.数组的排序
words = %w(the quick brown fox) #定义数组
words.sort #=> ["brown","fox","quick","the"] #sort进行排序
正常排序
a.sort #=> ["1", "2", "3", "5", "6", "four", "three", "two"]
另一方法比较排序 返回1
a.sort{|x,y| x.to_s <=> y.to_s} #=> ["1", "2", "3", "5", "6", "four", "three", "two"]
相反比较排序 返回-1
a.sort{|x,y| x.to_s <=> y.to_s} #=> ["two", "three", "four", "6", "5", "3", "2", "1"]
文件大小排列
files.sort{|x,y| File.size(x) <=> File.size(y)}

files.sort_by{|x| File.size(x)}
按名字,年龄,身高排列
lists.sort_by{|x| x.name,x.age,x.height}
--------------------------------------------------------------------
06.根据条件从数组中选择,(数组中查询)
x = [5,8,12,9,4,30]
x.detect{|e| e%6 ==0} #=>12 可以被6整除(取余为0的)
x.find{|e| e%2 ==0} #=>8 可以被2整除(取余为0的) 只返回第一个数组
x.find_all{|e| e%2 ==0} #=>[8,12,4,30] 可以被2整除(取余为0的) 返回所有满足条件的
x.select{|e| e%2 ==0} #=>[8,12,4,30] 可以被2整除(取余为0的) 返回所有满足条件的
取相反的
x.reject{|e| e%2 ==0} #=>[5,9] 可以被2整除(取余为0的) 返回所有满足相反条件的

正则查询
a = %w[January February March April May]
#=> ["January", "February", "March", "April", "May"]
a.grep(/ary/)
#=> ["January", "February"]
a.grep(/ary/){|i| i.length}
#=> [7, 8] 查询出来的内容转换为个数.

查询12到24之间的数平方
b = [1,20,5,7,13,33,15,28]
#=> [1, 20, 5, 7, 13, 33, 15, 28]
b.grep(12..24){|n| n*n}
#=> [400, 169, 225]

找最大最小
a.max #=> "May"
a.min #=> "April"

翻转一下对比结果
a.min{|x,y| x.reverse <=> y.reverse}
#=> "March"
a.max{|x,y| x.reverse <=> y.reverse}
#=> "February"

索引最大最小位置
a.index a.min
#=> 3
a.index a.max
#=> 4
--------------------------------------------------------------------
07.使用专门的索引函数
08.实现稀疏矩阵
参照<the ruby way>168页
--------------------------------------------------------------------
09.数组作为数字合集
删除重复项(uniq或uniq!)
a=[1,2,3,4,5]
b=[3,4,5,6,7]
c = a | b
#=> [1, 2, 3, 4, 5, 6, 7] "或"集合
d = a & b  "与"集合
#=> [3, 4, 5]
e = a - b
#=> [1,2] "差"集合
f = a |= b
#=> [1, 2, 3, 4, 5, 6, 7] 累积 等同 "或"集合

class Array
def ^(ohter)
(self | other) - (self & other)
end
end

x=[1,2,3,4,5]
y=[3,4,5,6,7]
z=x^y
#=>[1,2,6,7] 查不同

查是否存在
x = [1,2,3]
x.include? 2
#=>true
例如:
if x.include? 2
puts "yes"
else
puts "no"
end
例如: in
class Object
def in(other)
other.include? self
end
end
2.in x
#=>true 在x中有 2
例如:subset?
class Array
def subset?(other)
self.each do |x|
if !(other.include? x)
return false
end
true
end
def superset?(other)
other.subset?(self)
end
end
a=[1,2,3,4]
b=[2,3]
c=[2,3,4,5]
flag1=c.subset? a #false c是a的子集么?
flag2=b.subset? a #true b是a的子集么?
flag3=c.superset? b #true 相反b是c子集么?

定义通用集,执行差集
universe = [1,2,3,4,5,6]
a = [2,3]
b = universe - a

其他计算集合的 参照172页
--------------------------------------------------------------------
10.数组的随机化
class Array
def randomize
self.sort_by{rand}  #Kernel模块中的rand方法
end
def randomize!
self.replace(self.randomize)
end
end
x=[1,2,3,4,5]
y=x.randomize #=> [3,2,4,1,5]
x.randomize!  #=> x现在是[3,5,4,1,2] "叹号"意思直接修改自己

随机选取数组中一个元素
def pick_random
self[rand(self.length)]
end
x.pick_random #=> 2 随机返回一位,即 x[rand(x.length)]
--------------------------------------------------------------------
11.使用多位数组
class Array3
def initialize
@store =[[[]]]
end
def [][a,b,c]
if @store[a]==nil ||
@store[a][b]==nil ||
@store[a][b][c]==nil
return nil
else
return @store[a][b][c]
end
end
def []=(a,b,c,x)
@store[a] = [[]] if @store[a]=nil
@store[a][b] = [] if @store[a][b]=nil
@store[a][b][c] = x
end
end
x=Array3.new
x[0,0,0]=5
x[0,0,1]=6
x[1,2,3]=99
puts x[1,2,3]
--------------------------------------------------------------------
12.找出一个数组中而不再另一个数组用的元素(差集)
text = %w[the magic words are squeamish ossifrage]
#=> ["the", "magic", "words", "are", "squeamish", "ossifrage"]
dictionary = %w[an are magic the them these words]
#=> ["an", "are", "magic", "the", "them", "these", "words"]
unknown = text - dictionary
#=> ["squeamish", "ossifrage"]
--------------------------------------------------------------------
13.数组的变换或映射
x = %w[alpha bravo charlie delta echo foxtrot]
#=> ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot"]
a = x.collect{|w| w[0..0]}
#=> ["a", "b", "c", "d", "e", "f"]
a = x.collect{|w| w.length}
#=> [5, 5, 7, 5, 4, 7]
c = x.map{|w| w.length}
#=> [5, 5, 7, 5, 4, 7]
x.collect!{|w| w.upcase}
#=> ["ALPHA", "BRAVO", "CHARLIE", "DELTA", "ECHO", "FOXTROT"]
x.map!{|w| w.reverse}
=> ["AHPLA", "OVARB", "EILRAHC", "ATLED", "OHCE", "TORTXOF"]
--------------------------------------------------------------------
14.删除数组中的nil元素
a = [1,2,nil,3,nil,4,5]
#=> [1, 2, nil, 3, nil, 4, 5]
a.compact
#=> [1, 2, 3, 4, 5]
a.compact!
#=> [1, 2, 3, 4, 5]
a
#=> [1, 2, 3, 4, 5]
--------------------------------------------------------------------
15.删除数组中特定元素
a = [10,12,14,16,18]
#=> [10, 12, 14, 16, 18]
a.delete_at(3)
#=> 16 #删除第4位,返回被删除对象,如果不存在返回nil
a
#=> [10, 12, 14, 18]
a.delete(10)
#=>10 #返回10

x = %w[alpha bravo charlie delta echo foxtrot]
#=> ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot"]

x.delete("delta"){"不存在已经被删除"}
#=> "delta" #否则返回 "不存在已经被删除"

x.delete_if{|y| y.length==7}
#=> ["alpha", "bravo", "delta"] #删除指定条件的,没有修改返回nil 和reject!相似

a = x.slice(2)
#=> "charlie" #删除第3位

a = x.slice!(2)
=> "charlie"  #删除第3位,并修改x

x.pop
=> "foxtrot" #从数组最右侧开始删除,并修改x

x.shift
=> "alpha" #从数组最右侧开始删除,并修改x

arr = [1,2,3,4,5,6,7,8]
odd = arr.reject{|x| x%2 == 0}
#=>[1,3,5,7]  #用reject后接代码块

x.clear
#=>[]  #删除数组所有
--------------------------------------------------------------------
16.数组的拼接和附加(<< + -= concat)
x=[1,5,9]
#=> [1, 5, 9]
x << 13
#=> [1, 5, 9, 13]
x << 16 << 18
#=> [1, 5, 9, 13, 16, 18]  #主要时<< 这个符号加入附加

x=[1,2]
y=[3,4]
z=[5,6]

b=y+z
#=> [3, 4, 5, 6]
b +=x
#=> [3, 4, 5, 6, 1, 2]

z.concat y
#=> [5, 6, 3, 4]
--------------------------------------------------------------------
17.用数组用作栈或队列
push 在数组末尾添加
pop 在数组末尾删除
shift 删除数组开头元素
unshift 在开头添加元素
--------------------------------------------------------------------
18.对数组进行迭代
list=%w(i am chong mu)
list.each do |x|
p "#{x}"
end

按顺序迭代
words = %w(Son I am able she said)
#=> ["Son", "I", "am", "able", "she", "said"]
str=""
#=> ""
words.reverse_each{|w| str += "#{w} "}
#=> ["Son", "I", "am", "able", "she", "said"]
str
#=> "said she able am I Son" #返回反向字符串

将素和索引都传递给代码块
x=["alpha","beta","gamma"]
#=> ["alpha", "beta", "gamma"]
x.each_with_index do |x,i|
puts "Element #{i} is #{x}"
end
Element 0 is alpha
Element 1 is beta
Element 2 is gamma
=> ["alpha", "beta", "gamma"]

按随机对数组进行迭代
def random_each
temp = self.random
temp.each{|x| yield x}
end

words.random_each{|x| str += "#{x} "}
str #是一个随机的排列
--------------------------------------------------------------------
19.插入分隔符以形成字符串
words = %w(Son I am able she said)
#=> ["Son", "I", "am", "able", "she", "said"]
words.join(",")
#=> "Son,I,am,able,she,said"

words * " and "
#=> "Son and I and am and able and she and said"

list = %w[A B C D E F]
#=> ["A", "B", "C", "D", "E", "F"]
b=list[0..-2] * ", " + ", and " + list[-1]
#=> "A, B, C, D, E, and F"
--------------------------------------------------------------------
20.颠倒数组
a=[1,2,3]
#=> [1, 2, 3]
a.reverse
#=> [3, 2, 1]
a.reverse!
#=> [3, 2, 1]
a
#=> [3, 2, 1]
--------------------------------------------------------------------
21.删除数组中重复的元素
a=[2,3,3,2,6,5,9,8,7]
#=> [2, 3, 3, 2, 6, 5, 9, 8, 7]
a.uniq
#=> [2, 3, 6, 5, 9, 8, 7]
a
#=> [2, 3, 3, 2, 6, 5, 9, 8, 7]
a.uniq!
#=> [2, 3, 6, 5, 9, 8, 7]
a
#=> [2, 3, 6, 5, 9, 8, 7]
--------------------------------------------------------------------
22.数组的交织
a=[1,2,3,4]
#=> [1, 2, 3, 4]
b=["a","b","c","d"]
#=> ["a", "b", "c", "d"]
c=a.zip(b)
#=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
c
#=> [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
d=c.flatten 
#=> [1, "a", 2, "b", 3, "c", 4, "d"]
--------------------------------------------------------------------
23.计算数组中值的频率
class Array
def count
k=Hash.new(0)
self.each{|x| k[x]+=1}
k
end
end
meal=%w[spam spam eggs ham eggs spam]
items=meal.count
#items is {"ham"=>1,"spam"=>3,"eggs"=>2}
spams=items["spam"] #3
--------------------------------------------------------------------
24.将数组颠倒为散列
class Array
def invert
h={}
self.each_with_index{|x,i| h[x]=i}
h
end
end
a=["red","yellow","orange"]
#=> ["red", "yellow", "orange"]
a.invert
#=> {"orange"=>2, "red"=>0, "yellow"=>1}
--------------------------------------------------------------------
25.同步多个数组的排序
class Array
def sort_index
d=[]
self.each_with_index{|x,i| d[i]=[x,i]}
if block_given?
d.sort{|x,y| yield x[0],y[0].collect{|x| x[1]}}
else
d.sort.collect{|x| x[1]}
end
end
def sort_with(ord=[])
return nil if self.length!=ord.length
self.values_at(*ord)
end
end

a=[21,33,11,34,36,24,14]
b=a.sort_index
a2=a.sort_with(b)
c=a.sort_index{|x,y| x%2 <=> y%2}
a3=a.sort_with(c)

p a #[21,33,11,34,36,24,14]
p b #[2,6,0,5,1,3,4]
p a2 #[11,14,21,24,33,34,36]
p c #[6,5,4,3,2,1,0]
p a3 #[14,24,36,34,11,33,21]
--------------------------------------------------------------------
26.给新数组元素指定默认值
a = Array.new
#=> []
a[0]="x"
#=> "x"
a[3]="y"
#=> "y"
a
#=> ["x", nil, nil, "y"]
class ZArray < Array
def [](x)
if x >size
for i in size+1..x
self[i]=0
end
end
v = super(x)
end

def []=(x,v)
max=size
super(x,v)
if size - max > 1
(max..size-2).each do |i|
self[i]=0
end
end
end
end

num=ZArray.new
num[1]=1
num[2]=4
num[5]=25
#=>num is now [0,1,4,0,0,25]

分享到:
评论

相关推荐

    Ruby简明教程之数组和Hash介绍

    今天学习的是数组和Hash,数组在很多编程语言中都能常常用到。 数组: 数组是存储数据的一种容器,在Ruby中,数组中存储的数据可以是任何类型的数据;这和JAVA不同,在JAVA中,数组是存储同一类型数据的结构。 1. 在...

    Ruby数组(Array)学习笔记

    Ruby中的数组是动态数组,存储的数据不用限定类型,数组的长度是根据存储需要动态扩展,所以,在进行数据定义的时候,只用用最简单的方式new一个Array对象就可以了,可以使用以下几种方式: 代码如下: arr1=[] #最...

    Ruby新手学习书(Ruby语言中文教程)和Rails_4_days

    "Ruby新手学习书"和"Rails_4_days"这两个资源是为初学者设计的,旨在帮助他们快速掌握Ruby语言的基础以及Rails框架的核心概念。 在Ruby语言中文教程中,你将学到以下关键知识点: 1. **基础语法**:Ruby的语法简洁...

    ruby中文教程,从基础到深入的让你学习ruby

    在学习Ruby的过程中,你还需要了解一些工具,如Ruby的解释器irb(交互式Ruby环境)和ri/rdoc(Ruby文档工具),它们有助于调试和理解代码。版本管理工具如RVM(Ruby Version Manager)和rbenv可以帮助你管理多个Ruby...

    Ruby 学习指南.rar

    本"Ruby学习指南"旨在帮助初学者快速掌握Ruby的基础知识,同时也为有一定经验的开发者提供深入学习的资源。 1. **Ruby基础** - 变量:Ruby有五种变量类型,包括局部变量、实例变量、类变量、全局变量和常量,它们...

    ruby 数组使用教程

    在Ruby编程语言中,数组(Array)是一种非常重要的数据结构,它允许你存储多个值在...在实际开发中,你还会遇到更多高级特性和使用场景,例如迭代数组、查找特定元素、排序数组等,这都需要通过不断学习和实践来提高。

    Ruby自学笔记

    Ruby的数组可以通过转换为Hash,但这要求数组必须包含偶数个元素。具体操作时,使用星号(*)操作符配合Hash构造函数可以实现数组到Hash的转换。 在Ruby的方法中,如果方法名末尾带有感叹号(!),表示该方法会改变原有...

    个人ruby学习笔记

    从给定的文件信息中,我们可以提炼出一系列关于Ruby编程语言的重要知识点,涵盖基础语法、变量类型、...以上总结了Ruby的一些基础知识点,这些内容对于初学者掌握Ruby编程语言至关重要,同时也是进一步深入学习的基石。

    Ruby Data-Processing ruby数据处理

    3. **Ruby Select**: Select方法用于过滤数组中的元素,根据提供的条件返回满足条件的元素的新数组。例如,找出所有偶数: ```ruby numbers = [1, 2, 3, 4, 5] even_numbers = numbers.select { |n| n.even? } ...

    Ruby 教程 The Book of Ruby

    本书面向希望学习Ruby语言的初学者以及已经有一定编程基础但想深入了解Ruby特性的开发者。 - **风格**:本书采用实战导向的方式进行讲解,旨在通过实践让读者掌握Ruby的核心概念和技术。 - **目标读者**:适合对Ruby...

    精华ruby学习笔记和代码

    这个笔记里包含了ruby的整型,字符串,浮点数,布尔等基础数据类型,还有数组,哈希hash的用法, 类的定义,函数方法,以及对象定义,其他高级用法解释,除了笔记记录的语法糖之外,还包含了一些解释性的代码,帮助...

    笨办法学ruby_笨办法学ruby_ruby_bravevk4_

    此外,你还会学习到Ruby的模块系统,它是组织代码和实现命名空间的一种方式。 Ruby的块(blocks)和 Proc 对象是其独特之处,它们提供了简洁的回调函数和迭代器。书中会深入解释这些概念,并通过实例展示它们在实际...

    Programming Ruby 1.9 3rd edition

    ### Programming Ruby 1.9 3rd Edition:深入探索Ruby编程语言 #### 一、书籍概览 《Programming Ruby ...通过学习本书,读者将能够更好地理解Ruby的核心概念,并能够利用这些知识来构建高效、可靠的Ruby应用程序。

    Ruby资源ruby-v3.1.1.zip

    3. **Ruby编译器改进**:内部编译器的优化使得代码运行更快,同时减少了内存消耗,提升了整体性能。 4. **线程局部变量**:Ruby 3.1增加了对线程局部变量的支持,这些变量在每个线程中都有独立的副本,提高了多线程...

    Ruby入门教程中文PDF 附实例

    此外,Ruby的块(Block)和 Proc 对象让函数式编程变得简单,例如使用`each`方法遍历数组: ```ruby fruits = ["Apple", "Banana", "Cherry"] fruits.each { |fruit| puts fruit } ``` 元编程是Ruby的另一个强大特性...

    ruby基础学习资料

    Ruby支持五种基本的数据类型:符号(Symbol)、字符串(String)、数字(Numeric)、数组(Array)和哈希(Hash)。变量分为四种:局部变量(以小写字母或下划线开头)、实例变量(以`@`开头)、类变量(以`@@`开头...

    Ruby 简介及安装 视频教程

    2. **Ruby语法基础**:学习Ruby的基本语法结构,如变量(本地变量、实例变量、类变量、全局变量)、数据类型(字符串、数字、数组、哈希)、控制流(条件语句、循环)、函数和方法定义。 3. **面向对象编程**:理解...

Global site tag (gtag.js) - Google Analytics