如何在 Ruby 中初始化数组
在本文中,我们将学习如何在 Ruby 中初始化数组。有几种方法可以创建数组。让我们一一看看。
使用新的类方法:
新方法可用于在点运算符的帮助下创建数组。使用参数我们可以提供数组的大小和数组的元素。
没有任何争论——
# creating array using new method
# without passing any parameter
arr = Array.new()
# displaying the size of arrays
# using size method
puts arr.size
输出:
0
将数组的大小作为参数传递 -
# creating array using new method
# passing one parameter i.e. the
# size of array
arr2 = Array.new(7)
# displaying the length of arrays
# using length method
puts arr2.length
输出:
7
将数组和元素的大小作为参数传递 –
# creating array using new method
# passing two parameters i.e. the
# size of array & element of array
arr3 = Array.new(4, "GFG")
puts "#{arr3}"
输出:
["GFG", "GFG", "GFG", "GFG"]
使用字面量构造函数[] –
在 Ruby 中, []被称为字面量量构造函数,可用于创建数组。
# Ruby program to demonstrate the
# creation of array using literal
# constructor[] and to find the size
# and length of array
# creating array of characters
arr = Array['a', 'b', 'c', 'd', 'e', 'f']
# displaying array elements
puts "#{arr}"
# displaying array size
puts "Size of arr is: #{arr.size}"
# displaying array length
puts "Length of arr is: #{arr.length}"
输出:
["a", "b", "c", "d", "e", "f"]
[1, 2, 3, 4, 5, 6, 7]
Size of arr is: 6
Length of arr is: 6
使用范围 –
arr1 = ('1'..'6').to_a
# displaying array elements
puts "#{arr1}"
arr2 = *'11'..'15'
puts "#{arr2}"
输出:
["1", "2", "3", "4", "5", "6"]
["11", "12", "13", "14", "15"]