在 Ruby 中使用 Range 填充数组的正确方法 [英] Correct way to populate an Array with a Range in Ruby
本文介绍了在 Ruby 中使用 Range 填充数组的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读一本书,其中提供了使用to_a"方法将范围转换为等效数组的示例
I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods
当我在 irb 中运行代码时,我收到以下警告
When i run the code in irb I get the following warning
warning: default `to_a' will be obsolete
使用 to_a 的正确替代方法是什么?
What is the the correct alternative to using to_a?
是否有其他方法可以使用 Range 填充数组?
are there alternate ways to populate an array with a Range?
推荐答案
您可以使用 splat 创建具有范围的数组,
You can create an array with a range using splat,
>> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
使用Kernel
Array
方法,
Array (1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
或使用 to_a
(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
这篇关于在 Ruby 中使用 Range 填充数组的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文