Correct way to populate an Array with a Range in Ruby
You can create an array with a range using splat,
>> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
using Kernel
Array
method,
Array (1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
or using to_a
(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Create array in Ruby with begin value, end value and step for float values
For floats with custom stepping you can use Numeric#step like so:
-1.25.step(by: 0.5, to: 1.25).to_a
# => [-1.25, -0.75, -0.25, 0.25, 0.75, 1.25]
If you are looking on how to do this with integer values only, see this post or that post on how to create ranges and simply call .to_a
at the end. Example:
(-1..1).step(0.5).to_a
# => [-1.0, -0.5, 0.0, 0.5, 1.0]
Create array of n items based on integer value
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:
[*1..3, *?a..?c]
#=> [1, 2, 3, "a", "b", "c"]
how to create an array with ranges using an array with integer in ruby(rails)?
Add a helper value of -1, later on remove it.
array = [1,4,10,14,22]
array.unshift(-1)
ranges = array.each_cons(2).map{|a,b| a+1..b} #=>[0..1, 2..4, 5..10, 11..14, 15..22]
array.shift
How fast is Ruby's method for converting a range to an array?
The method is actually slightly worse than O(n). Not only does it do a naive iteration, but it doesn't check ahead of time what the size will be, so it has to repeatedly allocate more memory as it iterates. I've opened an issue for that aspect and it's been discussed a few times on the mailing list (and briefly added to ruby-core). The problem is that, like almost anything in Ruby, Range can be opened up and messed with, so Ruby can't really optimize the method. It can't even count on Range#size
returning the correct result. Worse, some enumerables even have their size
method delegate to to_a
.
In general, it shouldn't be necessary to make this conversion, but if you really need array methods, you might be able to use Array#fill instead, which lets you populate a (potentially pre-allocated) array using values derived from its indices.
How to select array elements in a given range in Ruby?
You can use ranges in the array subscript:
arr[100..200]
Related Topics
Devise Custom Routes and Login Pages
How to Stub Things in Minitest
How to Do Relative Time in Rails
Ruby: What Does the Comment "Frozen_String_Literal: True" Do
Getaddrinfo: Nodename Nor Servname Provided, or Not Known
Rails Each Loop Insert Tag Every 6 Items
Checking If a Variable Is Defined in Sass
How to Convert Datetime.Now to Utc in Ruby
Running a Command from Ruby Displaying and Capturing the Output
Purpose of "Consider_All_Requests_Local" in Config/Environments/Development.Rb
Flutter Pod Install Problem - Undefined Method 'Each_Child' For #≪Dir:0X00007Fa6F7E2Ec80≫
Change the Name of the :Id Parameter in Routing Resources for Rails
Set Utf-8 as Default String Encoding in Heroku