• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Ruby(2008-04-06)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

##########################  Containers   #############################
##########################  Arrays   #################################
#The class Array holds a collection of object references.
#You can create arrays by using literals or by explicitly creating an Array object.
#A literal array is simply a list of objects between square brackets.
a = [3.14, "pie", 99]
a.class   #Array
a.length  #3
a[0]      #3.14
a[3]      #nil

b = Array.new
b.class   #Array
b.length  #0
b[0] = "second"
b[1] = "array"

#Arrays are indexed using the [ ] operator. As with most Ruby operators, this is actually
#a method (an instance method of class Array) and hence can be overridden in subclasses.
a = [1, 3, 5, 7, 9]
a[-1]  #9
a[-2]  #7
a[-99] #nil

#You can also index arrays with a pair of numbers, [ start, count ]. This returns a
#new array consisting of references to count objects starting at position start.
a = [1, 3, 5, 7, 9]
a[1, 3]   #[3,5,7]
a[3, 1]   #[7]
a[-3, 2]  #[5,7]


#Finally, you can index arrays using ranges, in which start and end positions are separated
#by two or three periods. The two-period form includes the end position, and the
#three-period form does not.
a = [1, 3, 5, 7, 9]
a[1..3]  #[3,5,7]
a[1...3] #[3,5]

#The [ ] operator has a corresponding [ ]= operator, which lets you set elements in the array.
a = [1, 3, 5, 7, 9]
a[1] = "bat"
a[3] = [9, 8]

a = [1, 3, 5, 7, 9]    
a[2, 2] = 'cat'   #[1,3,'cat',9]
a[2, 0] = 'dog'   #[1,3,'dog','cat',9]
a[1,1] = [9,8,7]  #[1,9,8,7,'dog','cat',9]
a[0..3] = []      #['dog', 'cat', 9]
a[5..6] = 99, 98  #['dog', 'cat', 9, nil, nil, 99, 98]
#Arrays have a large number of other useful methods. Using these, you can treat arrays
#as stacks, sets, queues, dequeues, and fifos.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ruby爬虫发布时间:2022-07-14
下一篇:
rubyonrails修改配置文件或修改yml文件的内容发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap