Ruby编程之数组索引、数组拷贝与克隆
【摘要】 笔者主要用RubyMine介绍了Ruby数组索引、数组拷贝与克隆
arr = ['h','e','l','l','o',' ','w','o','r','l','d']
print( arr[0,5] ) #=> hello (or) ["h", "e", "l", "l", "o"]
print( arr[-5,5 ] ) #=> world (or) ["w", "o", "r", "l", "d"]
print( arr[0..4] ) #=> hello (or) ["h", "e", "l", "l", "o"]
print( arr[-5..-1] ) #=> world (or) ["w", "o", "r", "l", "d"]
p( arr[0,5] ) #=> ["h", "e", "l", "l", "o"]
p( arr[0..4] ) #=> ["h", "e", "l", "l", "o"]
["h", "e", "l", "l", "o"]["w", "o", "r", "l", "d"]["h", "e", "l", "l", "o"]["w", "o", "r", "l", "d"]["h", "e", "l", "l", "o"]
["h", "e", "l", "l", "o"]
arr = []
arr[0] = [0]
arr[1] = ["one"]
arr[3] = ["a", "b", "c"]
puts(arr[0])
puts(arr[1])
puts(arr[3])
arr2 = ['h','e','l','l','o',' ','w','o','r','l','d']
arr2[0] = 'H'
arr2[2,2] = 'L', 'L'
arr2[4..6] = 'O','-','W'
arr2[-4,4] = 'a','l','d','o'
puts(arr2[0])
puts(arr2[2,2])
puts(arr2[4..6])
puts(arr2[-4,4])
0
one
a
b
c
H
L
L
O
-
W
a
l
d
o
arr1=['h','e','l','l','o',' ','w','o','r','l','d']
arr2=arr1 # arr2 is now the same as arr1.
# Change arr1 and arr2 changes too!
arr3=arr1.clone
# arr3 is a copy of arr1.
# Change arr3 and arr2 is unaffected
puts(arr1)
puts(arr2)
puts(arr3)
h
e
l
l
o
w
o
r
l
d
h
e
l
l
o
w
o
r
l
d
h
e
l
l
o
w
o
r
l
d
开发环境:Rubymine
The book of Ruby----A hands-on guide for the Adventurous---[美]Huw Collingbourne---no starch press
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区),文章链接,文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:cloudbbs@huaweicloud.com进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
- 点赞
- 收藏
- 关注作者
评论(0)