Ruby 学习(六)数组Array

自强不息系列之Ruby 数组(Array)介绍 Ruby 数组(Array) Ruby 数组是任何对象的有序整数索引集合。数组中的每个元素都与一个索引相关,并可通过索引进行获取。 数组的索引从 0 开始,这与 C 或 Java 中一样。一个负数的索相对于数组的末尾计数的,也就是说,索引为 -1 表示数组的最后一个元素,-2 表示数组中的倒数第二个元素,依此类推。 Ruby 数组可存储诸如 String、 Integer、 Fixnum、 ... 阅读详情

数组 []

基础

  • 数组通过[]索引访问
  • 通过赋值操作插入、删除、替换元素
  • 通过+,-号进行合并和删除元素,且集合做为新集合出现
  • 通过<<号向原数据追加元素
  • 通过*号重复数组元素
  • 通过|和&符号做并集和交集操作(注意顺序)

索引

  • 从 0 开始
  • 负数的索引是从尾部开始计数的,索引为 -1 表示数组的最后一个元素

常用API

创建

初始化一个空数组

names = Array.new

指定的值初始化

nums = Array[1, 2, 3, 4,5]

数组的大小 size length


例子

names = Array.new
puts "#{names.size}" 
puts "#{names.length}"

输出

0
0

判断是否为空 array.empty?

  • true: 空数组
  • false: 非空数组
names = Array["one", "two", "three", "four"]
puts "#{names.empty?}" # false
names.clear
puts "#{names.empty?}" # true

&

返回一个新的数组,包含两个数组中共同的元素,没有重复。

names = Array["one", "two", "three", "four"]
names2 = Array["three", "four", "five"]

array = names & names2
puts array

输出

three
four

*

array * int

数组重复 int 次

names = Array["one", "two", "three", "four"]

array = names * 2
puts array

输出

one
two
three
four
one
two
three
four

array * str

数组中的元素通过 str 拼接

names = Array["one", "two", "three", "four"]

array = names * '-'
puts array

输出

one-two-three-four

+

两个数组进行拼接

names = Array["one", "two", "three", "four"]
names2 = Array["three", "four", "five"]

array = names + names2
puts array

输出

one
two
three
four
three
four
five

-

A - B

从数组 A 中 移除在数组 B 中出现的元素

例子

names = Array["one", "two", "three", "four"]
names2 = Array["three", "four", "five"]

array = names - names2
puts array

输出

one
two

|

A | B

把数组B中的元素添加到A中,但是会移除重复的元素

例子

names = Array["one", "two", "three", "four"]
names2 = Array["three", "four", "five"]

array = names | names2
puts array

输出

one
two
three
four
five

<<

把元素添加到数组的末尾

例子

names = Array["one", "two", "three", "four"]

array = names << "new"
puts array

输出

one
two
three
four
new

==

数组相等的判断

获取元素

array[index]

  • 获取 index 位置处元素
  • 超过范围会为空
  • 负数表示从末尾开始取元素
names = Array["one", "two", "three", "four"]

puts names[0]  # one
puts names[2]  # three
puts names[3]  # four
puts names[4]  # 
puts names[-1] # four
puts names[-2] # three

array[start, length]

  • 从 start 位置开始(包含这个位置),获取 length 个元素
  • 超过范围会只返回数组最大元素
names = Array["one", "two", "three", "four"]

puts "1 ====="
puts names[0, 1]  
puts "2 ====="
puts names[0, 2]  
puts "3 ====="
puts names[0, 3]  
puts "4 ====="
puts names[0, 4]  
puts "5 ====="
puts names[0, 5] 

输出

1 =====
one
2 =====
one
two
3 =====
one
two
three
4 =====
one
two
three
four
5 =====
one
two
three
four

array[range]

获取 range 范围内的元素

names = Array["one", "two", "three", "four"]

puts names[0..2]  

输出

one
two
three

array.at(index)

等价于array[index]

names = Array["one", "two", "three", "four"]

puts names.at(2)
three

array.slice(index)

array.slice(start, length)

array.slice(range)

array.fetch(index)

  • 获取 index 位置处的元素,
  • 如果index超过索引范围,会抛出异常 IndexError

names = Array["one", "two", "three", "four"]
puts "#{names.fetch(0)}"
one

names = Array["one", "two", "three", "four"]
names.fetch(10)
/Users/ocean/Desktop/code/ruby/learn/one/one.rb:2:in `fetch': index 10 outside of array bounds: -4...4 (IndexError)

array.fetch(index, default)

  • 获取 index 位置处的元素,
  • 如果index超过索引范围,会返回默认值 default
names = Array["one", "two", "three", "four"]
puts "#{names.fetch(10, "default")}"
default

array.fetch(index) { |index| block }

  • 获取 index 位置处的元素,
  • 如果index超过索引范围,会调用block
names = Array["one", "two", "three", "four"]
res = names.fetch(10) do |index|
  return  "#{index} new"
end
print res

array.first

  • 获取第一个元素
  • 如果数组为空,返回 nil
names = Array["one", "two", "three", "four"]
print names.first
one

array.first(n)

  • 获取前 n 个元素
names = Array["one", "two", "three", "four"]
print names.first(3)
["one", "two", "three"]

array.last

  • 获取最后一个元素
  • 如果数组为空,返回 nil
names = Array["one", "two", "three", "four"]
puts names.last
four

array.last(n)

  • 获取后n个元素
names = Array["one", "two", "three", "four"]
puts names.last(2)
three
four

添加元素

array.concat(other_array)

把数组other_array中的元素追加到数组array中

names = Array["one", "two", "three", "four"]
names2 = Array["new", "12"]
puts names.concat(names2)
one
two
three
four
new
12

插入元素 array.insert(index, obj...)

  • 在给定的 index 的元素前插入给定的值
  • index 可以是负值。
names = Array["one", "two", "three", "four"]
names.insert(2, "new")

puts names
one
two
new
three
four

array.push(obj, ...)

在末尾添加元素 obj

names = Array["one", "two", "three", "four"]
names.push("tem")
puts names
one
two
three
four
tem

修改元素

array[index] = obj

修改index位置处的元素为obj

names = Array["one", "two", "three", "four"]
names[1] = "new"
puts names 

输出

one
new
three
four

array[start, length] = obj or an_array or nil

  • 把 start 开始 length长度的元素替换为 元素obj,或者数组an_array,或者空nil

names = Array["one", "two", "three", "four"]
names[0,2] = "new"
puts names 

输出

new
three
four

names = Array["one", "two", "three", "four"]
names[0,2] = Array["new1", "new2", "new3", "new4"]
puts names 

输出

new1
new2
new3
new4
three
four

array[range] = obj or an_array or nil

删除元素

array.clear

移除所有的元素

names = Array["one", "two", "three", "four"]
names.clear
puts names

array.compact

移除了所有的nil元素

array.delete(obj) array.delete(obj) { block }

删除指定的元素

names = Array["one", "two", "three", "four"]
names.delete("two")
puts names
one
three
four

array.delete_at(index)

删除指定位置处的元素,如果超过数组大小,返回nil

names = Array["one", "two", "three", "four"]
names.delete_at(3)
puts names
one
two
three

array.delete_if { |item| block }

删除满足条件的元素

names = Array["one", "two", "three", "four"]
names.delete_if { |item| item == "two" }
puts names
one
three
four

array.shift

删除第一个元素

names = Array["one", "two", "three", "four"]
names.shift
puts names
two
three
four

array.pop

删除最后一个元素

names = Array["one", "two", "three", "four"]
names.pop
puts names
one
two
three

查找

包含元素 array.include?(obj)

names = Array["one", "two", "three", "four"]
print names.include?("two") # true
print names.include?("ten") # false

元素的索引 array.index(obj)

  • 获取元素的索引
  • 没有找到返回nil
names = Array["one", "two", "three", "four"]
puts "#{names.index("two")}" # 1
puts "#{names.index("ten")}" # nil

最后一个元素的索引 array.rindex(obj)

names = Array["one", "two", "three", "two"]
puts "#{names.index("two")}" # 1
puts "#{names.rindex("two")}" # 3

array.replace(other_array)

数组替换为其他数组

names = Array["one", "two", "three", "four"]
names2 = Array["ten", "new"]
names.replace(names2)
puts names
ten
new

遍历

array.map { |item| block }

转换为新一个数组

names = Array["one", "two", "three", "four"]
array = names.map{ |i| "#{i}" + "_new" }
puts array

输出

one_new
two_new
three_new
four_new

array.collect { |item| block }

转换为一个新的数组

array.each { |item| block }

遍历元素,传递的是元素

names = Array["one", "two", "three", "four"]
names.each do |item|
    puts "元素: #{item}"
end
元素: one
元素: two
元素: three
元素: four

array.each_index { |index| block }

遍历元素,传递的是索引

names = Array["one", "two", "three", "four"]
names.each_index do |idx|
  puts "idx: #{idx}, value: #{names[idx]}"
end
idx: 0, value: one
idx: 1, value: two
idx: 2, value: three
idx: 3, value: four

array.select {|item| block }

查找 block 返回true的元素

names = Array["one", "two", "three", "two"]
res = names.select { |item|
  item.include?("o")
}
puts res
one
two
two

删除重复的元素 array.uniq

names = Array["one", "two", "three", "four", "one"]
puts names.uniq
one
two
three
four

元素拼接 array.join(sep=$,)

names = Array["one", "two", "three", "four"]
puts names.join("--")
one--two--three--four

反转 array.reverse

names = Array["one", "two", "three", "four"]
puts names.reverse
four
three
two
one

排序

array.sort

names = Array["one", "two", "three", "four"]
puts names.sort
four
one
three
two

array.sort { | a,b | block }

“傻瓜”stata入门——熟悉操作界面 小白开始学习stata和matlab,零基础上手 阅读详情

相关推荐

ArcGIS中地理坐标系与投影坐标系以及投影转换

简单介绍arcgis软件中坐标系定义、设置和常见问题。

weixin_41399650的博客 8万+

【Ruby学习笔记】10.Ruby 数组(Array)

Ruby 数组是任何对象的有序整数索引集合。数组中的每个元素都与一个索引相关,并可通过索引进行获取。

qq_62052372的博客 1349

1.深入浅出:理解三极管截止、放大和饱和状态!——参考《模拟电子技术基础》清华大学华成英主讲

幼儿园水平理解三极管截止、放大和饱和状态!书上看不懂,听课听不懂的过来! 绕不开的三极管结构 以NPN为例,晶体三极管的结构,这是很多人不想看的,但是确实是非常重要的!不看结构是理解不了工作原理的! (这样记忆:N是negative,负,代表多子为电子;P是positive,正,代表多子为空穴) 注意观察三极管的结构,有助于理解工作时的状态。 两张图结合起来看,略作解释: 1.图中空心为空穴带正...

Hardware_harder的博客 4万+

ruby学习---数组类(Array)

1,数组的创建    (1)使用[ ]来创建数组                      num = [2,3,4,5,6]                        str =  ["a","d","c" ]     (2)使用Array.new 来创建     (3)使用%w与%i来创建 2,to_a方法。    对散列对象使用to_a方法,结果会得到相应的数组的数组。

TEC-L的博客 481

Win11下Python脚本不执行?5分钟搞定PATH环境变量配置(VSCode终端实测)

本文针对Win11系统下VSCode终端中Python脚本执行无响应的问题,提供了详细的诊断与解决方案。核心在于正确配置PATH环境变量,通过图形化界面调整Python路径优先级,并分享了VSCode终端环境变量的刷新技巧,帮助开发者在5分钟内快速解决环境配置难题。

weixin_28358083的博客 384

Skynet 框架面试题

本文整理了游戏服务端开发面试中 Skynet 框架的高频考点,涵盖底层架构、消息派发、协程调度、网络 I/O、harbor 跨机通信、内存管理、socket 处理、阻塞操作、错误处理等核心内容。全面覆盖 Skynet 框架的原理、使用和实战问题,追求深入准确,拒绝八股文。

小赖的博客 383

Ruby 数组(Array)

Ruby数组是强大的有序数据结构,支持存储多种类型元素。文章介绍了数组的创建方式(字面量、Array.new、%w/%i)、访问修改方法(索引、范围操作)以及常用操作(添加/删除、查询、排序、合并等)。重点讲解了each、map、select等迭代方法,以及多维数组和Enumerable模块的应用。最后强调了数组的可变性特点和使用注意事项,并提供了综合应用示例。Ruby数组通过丰富的方法极大简化了数据处理流程。

likuoelie的博客 1109

详解【异质图卷积网络 RGCN】回顾:图神经网络问题的三大处理步骤 | 从起源说起,RGCN核心公式解释,两种降低模型参数量/优化的方式,附核心代码实现讲解

本篇,我们深入分析和学习RGCN的原理以及为何要这么做。首先让我们来回顾对于图神经网络问题的三大处理步骤,可以说,这是该深度学习模型的基本理解,后续都是在深化其中的细节处理。然后以容易理解的方式,引出异质图卷积网络RGCN的由来,主要讲解其核心公式和论文中作者所提出的两种降低模型参数量/优化的处理办法,并给出基础分解以及块对角分解的核心实现代码讲解。最后附上RGCN源代码及说明。

追光者♂:记录、分享、总结、提升,现象级专栏《Python从入门到人工智能》作者,无惧黑暗,坚信曙光 1280

ruby array_在Ruby中使用Array.new(Array_object)创建数组

ruby arrayIn the previous article, we have learned how we can declare an Array class instance with the help of Array.new(size, obj) method? You can also notice that in the program codes written to dem...

cumt30111的博客 503

【异常】OpenClaw提示Message ordering conflict - please try again. If this persists, use /new to start a fr

摘要:OpenClaw助手出现"Message ordering conflict"异常时,表明会话消息排序冲突,主要由消息队列时序错乱、会话同步异常或上下文过载引起。解决方案包括:1)基础重试暂停后单发指令;2)最优方案是发送/new重置会话;3)极端情况下需重启客户端或检查指令格式。预防建议包括避免高频并发指令、定期重置会话及确保网络稳定。该报错属业务层异常,不影响账号安全。

奶爸的编程之路,也就一周冷个三天 424

基于VisionMaster实现数据实时存储至MySQL (二)

摘要:之前的分享主要聚焦于简单的一维数据实时存储。但在做缺陷检测项目时,情况往往更加复杂:一张检测图像中可能同时存在多个缺陷,每个缺陷都有一组独立的核心参数(如质心、长短轴、面积等)。如何在 MySQL 中记录这些成组出现的缺陷数据,而不只是简单的单条记录?

haier123888的博客 226

ruby的Array总结

ruby的Array总结   2010-12-28 11:25:54|  分类: Ruby/Rails|字号 订阅 Array 作为一个类,其中方法有:(简单的就不想说明了,仅作参考) 方法 说明 调用举例 其他 [] 将返回一个新array类对象

327

AIGC实战——多模态模型DALL.E 2

DALL.E 2 是 OpenAI 提出的一个大规模文本生成图像模型,可以根据文本提示生成各种风格的逼真图像。它通过将预训练模型 CLIP 与 GLIDE 中的扩散模型架构相结合完成任务。它还具有其他应用,例如通过文本提示编辑图像和提供给定图像的变体。虽然它也有一些局限性,例如不一致的文本渲染和属性绑定,但 DALL.E 2 是仍然一个非常强大的AI模型,推动了生成模型的发展。

盼小辉丶的博客 1万+

ruby array_在Ruby中使用Array.pop和Array.shift方法从Array中删除元素

ruby array Ruby Array.pop和Array.shift方法 (Ruby Array.pop and Array.shift methods) If you are reading an article that is related to deleting elements from the instance of Array class then it is expected...

cumt951045的博客 463

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

ruby array_在Ruby中使用Array.delete()和Array.delete_at()从Array中移除元素

ruby array Ruby Array.delete()和Array.delete_at()方法 (Ruby Array.delete() and Array.delete_at() methods) In the last article, we have seen how we can remove the elements from an instance of Array class ...

cumudi0723的博客 811

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

ruby array_Ruby中带有示例的Array.index()方法

ruby array Array.index()方法 (Array.index() Method) In this article, we will study about Array.index() method. You all must be thinking the method must be doing something which is related index of certa...

cumudi0723的博客 874

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

ruby array_在Ruby中使用Array.first和Array.last方法访问数组的第一个和最后一个元素...

ruby arrayIn Ruby, you have the privilege to access the first and last method of an array directly without putting some different logic for it with the help of Array.first and Array.last methods. 在Ru...

cumtv80668的专栏 905

ruby array_Ruby中带有示例的Array.select方法

ruby array Array.select方法 (Array.select Method) In the last articles, we have seen how to iterate over the instances of Array class? We have seen that we have got methods like Array.each, Array.revers...

cumtb2002的博客 442

ruby一维数组转二维数组_在Ruby中创建二维数组

ruby一维数组转二维数组 Ruby二维数组 (Ruby Two Dimensional Array) So far we have discussed single-dimensional Array instances or 1D Array instances in Ruby. We have seen how we can declare them and how we can imple...

cumt30111的博客 857

ruby array_Ruby中带有示例的Array.zip()方法

ruby array Array.zip()方法 (Array.zip() Method) In this article, we will study about Array.zip() Method. You all must be thinking the method must be doing something which is related to zipping values of...

cumt951045的博客 356

ruby学习之Array

ruby中数组的大小是可以随时改变的,数组中的元素只会保存对对象的引用。 一、定义 a=Array.new() a=Array.new(5)   创建5个nil元素的数组 a=Array.new(5,1) 创建5个初始值为1的数组 a=[] a=[1,2,”a”] %w(a b c d ab)用来创建字符串数组,不过无法处理带空格的字符串

全能小码农 1192

ruby 数组长度统计_在Ruby中找到数组长度的不同方法

ruby 数组长度统计If you are reading an article that is related to obtaining information about the instance of Array class then it is expected from you that you are aware of the basic things related to Array...

1030

Ruby学习之模块数组(Array)的定义和使用

Ruby 数组是任何对象的有序整数索引集合,其中的每个元素都与一个索引相关,并可通过索引进行获取,它的索引从 0 开始,这与 C 或 Java 中一样。一个负数的索相对于数组的末尾计数的,也就是说,索引为 -1 表示数组的最后一个元素,-2 表示数组中的倒数第二个元素,依此类推,它可存储诸如 String、 Integer、 Fixnum、 Hash、 Symbol 等对象,甚至可以是其他 Arr...

luyaran的博客 735

ruby array_在Ruby中使用Array.at()方法访问Array的元素

ruby arrayWe are very well known with the way to declare an Array in Ruby or you can say that how we can create an instance of Array class? We also know that Ruby has got a wealthy library where you c...

cumubi7552的博客 332
上一篇: Ruby 学习(五)字符串String
下一篇: Ruby 学习(七)哈希类型Hash
zhhelnice
博客等级 码龄10年 7粉丝 48原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值