I need to dynamically retrieve a slice of size 3 from an array (as part of a more complex method):
a = %w(a b c d e)
i = 0 # i is an argument, I need [nil, "a", "b"]
a[(i-1)..(i+1)]
=> [] # no luck
a[(i-1), 3]
=> ["e"]
I know that when code gets messed up, it's not ruby's fault, is mine. What I'm missing? Is there a better way to achieve this?
I need to clarify. What I want is a slice of a given size, around a given index, and maping to nil if the slice goes beyond offset.
i=0, what do you expect? ['a', 'b','c'] ? or ['a', nil, nil]? why your expect is ['e', nil, nil]?ì), I want to return[a[i-1],a[i],a[i+1]], with nil if index goes offset or negative, that's what I mean with 'around'. The problem is that ruby doesnt return nil on negative indexes.