I want to build an array using range (0..x) while excluding certain ranges and values.
Example:
array = [1, 2, 3, .., 50, 60, .., 98, 100] How is this done?
Your example is:
array = [1, 2, 3,..., 50, 60,..., 98, 100] If this means array is to contain the numbers 1 through 50, 60 through 98 and 100, then you can write that:
array = [*1..50, *60..98, 100] #=> [1, 2, 3,...49, 50, 60, 61, 62,...98, 100] [*1..50, *([*60..100]-[99])]. Is that what you had in mind?Subtracting one range from another:
(1..100).to_a - (51...60).to_a To remove additional specific values, create an array of those values and subtract them too:
(1..100).to_a - (51...60).to_a - [82, 56, 23] To add some cleanliness:
values_to_remove = [(51..60), [34,67,98]].flat_map(&:to_a) (1..100).to_a - values_to_remove Since Rails 6, you can build the example array in question using ranges + excluding:
(1..100).excluding(*(51..59), 100) I want to build an array using range (0..x) while excluding certain ranges and values.
As per ruby-docs, you can excluded a range using Enumerable#grep_v:
(1..10).grep_v(2..4) #=> [1, 5, 6, 7, 8, 9, 10] grep_v only defines one parameter so to exclude more than one range you would have to do something like:
(1..10).grep_v(2..4).grep_v(6..8) #=> [1, 5, 9, 10] Values can be used as the argument if a range is not required e.g. grep_v(1).