2

I have trouble understanding this since I'm not very familiar with Ruby and I need to convert this code to C#:

gifts[(position + 1)..-1] = []

gifts is an array, but what does this line do? Does it remove elements from (position + 1) to -1, or marks them as an empty element?

What I'm using is:

gifts.RemoveRange(0, position + 1);
3
  • If there is something particularly unclear about the documentation of Array#[]=, I'm sure the Ruby team would be happy to know about it! Commented Mar 25, 2015 at 9:09
  • @JörgWMittag: I think here it is the odd special-casing of parsing a Range end point . . . because e.g. 5..-1 will do different things inside and outside of [ ] Commented Mar 25, 2015 at 9:11
  • Yeah, array slicing doesn't care about the contents of the range (which in this particular case is just empty), only the start and endpoint. Makes sense, but is non-obvious. Commented Mar 25, 2015 at 9:25

2 Answers 2

3

This Ruby code gifts[(position + 1)..-1] = [] removes entries from position + 1 to -1 which is "last element of array" in Ruby.

So equivalent code in C# will be

gifts.RemoveRange(position + 1, gifts.Count- position - 1);
Sign up to request clarification or add additional context in comments.

Comments

3

The ruby snippet will remove everything after position:

gifts = [1,2,3,4,5];
gifts[2..-1] = [];
gifts; // [1, 2]

An equivalent C# snippet (using LINQ) would be:

gifts = gifts.Take(position+1).ToList();

Or, if you want to modify the list in-place (no LINQ required):

gifts.RemoveRange(position + 1, list.Count - position - 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.