1

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?

1
  • What are the certain values you want to exclude? Commented Feb 6, 2015 at 1:42

4 Answers 4

7

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] 
Sign up to request clarification or add additional context in comments.

2 Comments

98 to 100 was meant to highlight the exclusion of 99. Is the only way to exclude using this method, to stop an array and begin a new one?
You could write [*1..50, *([*60..100]-[99])]. Is that what you had in mind?
2

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 

3 Comments

How about specific values ie non ranges? @Brennan
Is there a way to remove the redundancy of .to_a? @Brennan
edited again. Unfortunately, when dealing with ranges, there must be at least a little to_a action going on.
2

Since Rails 6, you can build the example array in question using ranges + excluding:

(1..100).excluding(*(51..59), 100) 

2 Comments

Welcome to SO. Do you have a reference to this Range#excluding method? I don't see it in the latest docs.
@eeeeeean Edited with clarification of this method being available in Rails since version 6
1

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.