ruby 基于整数值创建 n 个项目的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11173173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:13:47  来源:igfitidea点击:

Create array of n items based on integer value

ruby

提问by Martin

Given I have an integer value of, e.g., 10.

鉴于我有一个整数值,例如,10

How can I create an array of 10 elements like [1,2,3,4,5,6,7,8,9,10]?

如何创建一个包含 10 个元素的数组,例如[1,2,3,4,5,6,7,8,9,10]

回答by Michael Kohl

You can just splat a range:

你可以只喷一个范围:

[*1..10]
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Ruby 1.9 allows multiple splats, which is rather handy:

Ruby 1.9 允许多个 splats,这很方便:

[*1..3, *?a..?c]
#=> [1, 2, 3, "a", "b", "c"]

回答by Dzmitry Plashchynski

yet another tricky way:

另一个棘手的方法:

> Array.new(10) {|i| i+1 }
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

回答by Darshan Rivka Whittle

def array_up_to(i)
    (1..i).to_a
end

Which allows you to:

这使您可以:

 > array_up_to(10)
 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

回答by Alexander.Iljushkin

About comments with tricky methods:

关于使用棘手方法的评论:

require 'benchmark'

Benchmark.bm { |x|
  x.report('[*..] ') do
    [*1000000 .. 9999999]
  end  

  x.report('(..).to_a') do
    (1000000 .. 9999999).to_a
  end

  x.report('Array(..)') do
    Array(1000000 .. 9999999)
  end

  x.report('Array.new(n, &:next)') do
    Array.new(8999999, &:next)
  end

}

Be careful, this tricky method Array.new(n, &:next)is slower while three other basic methods are same.

请注意,这种棘手的方法Array.new(n, &:next)较慢,而其他三种基本方法相同。

                           user     system      total        real
[*..]                  0.734000   0.110000   0.844000 (  0.843753)
(..).to_a              0.703000   0.062000   0.765000 (  0.843752)
Array(..)              0.750000   0.016000   0.766000 (  0.859374)
Array.new(n, &:next)   1.250000   0.000000   1.250000 (  1.250002)

回答by Sin Nguyen

You can do this:

你可以这样做:

array= Array(0..10)

If you want to input, you can use this:

如果你想输入,你可以使用这个:

puts "Input:"
n=gets.to_i
array= Array(0..n)
puts array.inspect