0

I'm going through the code on a sample solution to my first Ruby Quiz (The Solitaire Cipher), and ran across this little nugget:

def move_down( index )
    if index == @deck.length - 1
        @deck[1..1] = @deck[index], @deck[1]
        @deck.pop
    else
    ...
    end
end

The person who wrote this solution apparently used the multiple assignment in the second line to insert @deck[index] into the position before @deck[1]. Why not just use this?

@deck.insert(1, @deck[index])

Is there a difference?

3
  • 1
    he is mutating the array element in place replacing it with an array of 2 elements, e.g: a = [1,2,3]; a[2] = a[0], a[1]; a #=> [1, 2, [1, 2]] Commented Jan 22, 2016 at 1:50
  • @bjhaid That's not what the code in the question does. No nested array is produced (tested with Ruby 2.2.1). Commented Jan 22, 2016 at 6:00
  • 1
    There is no difference in effect. There is a huge difference in legibility: @deck.insert(1, @deck[index]) is obvious, whereas the other code is too clever by half. Commented Jan 22, 2016 at 6:06

1 Answer 1

1

OK, now I see what you mean. Sure, they will give the same result. I guess it just would be matter of choosing which style is more clear for you, or how you think your code would be easier to understand and in consequence more maintainable.

If your question is about which method is more "performant" I don't know that answer and I don't think it evens matters, as ruby is not meant to be performant but to be expressive.

Sign up to request clarification or add additional context in comments.

1 Comment

Oops! @deck.index was a typo that has since been edited out. To clarify: the goal is to make the first three elements of @deck equal to [@deck[0], @deck[index], @deck[1]...]. The first code block does this by replacing @deck[1] with @deck[index], @deck[1]. The second does this by inserting @deck[index] between @deck[0] and @deck[1]. Your code would make the first four terms [@deck[0], @deck[index], 1, @deck[1]...], which is not the same thing. Unless I missed something?

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.