2

I have a ruby array of, say, 10 elements, and I'd like to return all but the 5th element.

a = *(1..10) 

I'd like to be able to do something like

a[0..3 + 5..9] 

Or even better something like (borrowing from the R syntax),

a[-4] 

to do this, but that doesn't work. (Nor does anything more clever I've tried like getting an array of the element indices). What's the best way to do this in ruby?

2
  • 2
    what's the problem with the trivial a[0..3] + a[5..9]? Commented Aug 21, 2012 at 23:23
  • It seems very rare that you would need such functionality. Can you talk more about what you're doing? e.g. how do you know you want to omit index 4? If you are tracking offsets, there is probably a better data structure. If you're finding it dynamically before you build this new array, then there's almost certainly better ways to accomplish this process using the Enumerable methods (e.g. (1..10).reject { |element| element == 5 }) Commented Aug 21, 2012 at 23:33

3 Answers 3

5

You can use values_at: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-values_at

so you may use it as

a.values_at(0..3, 5..9) 
Sign up to request clarification or add additional context in comments.

Comments

4

No black magic required:

a[0..3] + a[5..9] 

2 Comments

Not really the best solution here IMO because this doesn't work when your index to omit is the first or last index in the array.
@Calvin: this? a[0...n] + a[n+1...a.length]
1

Look in the documentation under Array#delete_at

For example, myarray.delete_at(5) results in the array lacking what was element 5 (counting from 0, of course).

Example:

class Array def without(n) self.delete_at(n) return self end end arr = [1, 2, 3, 4] p arr.without(1) #=> [1, 3, 4] 

However, as a commenter points out, this alters the original array, which may not be what the O.P. wants! If that's an issue, write it like this:

class Array def without(n) arr2 = Array.new(self) arr2.delete_at(n) return arr2 end end 

That returns the desired array (an array lacking the nth element of the original) while leaving the original array untouched.

5 Comments

There are two problems with that: 1. it changes the original array and, 2. it doesn't return the array without removed element but it returns the removed element.
revised to incorporate that part of the spec :)
Looks nice but try p arr.without(1) #=> [1, 3, 4]; p arr #=> [1, 3, 4] unfortunately because delete_at changes the original array.
Oh, I see. Sorry, I thought that was what he wanted done. Now I see what you're getting at. Modified answer further to point out this flaw.
Updated solution looks good here and should be the accepted answer - one thing to note is that this is built into ActiveSupport for rails 5+ users :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.