Feature #10701
openClass:Array 2 New methods
Description
Hi,
New to this, but this is an Array method that I use a lot and thought it might be included in a release, it's basic, but very helpful when you need to rotate certain defined values ie. log rotation with monthly timestamps
class Array
def next(value)
#Returns next element value (and loop to the beginning if last element is matched ) based on first input found. if not found, returns first value of array
self[((self.index(value)||-1)+1)%self.size]
end
def prev(value)
#Returns previous element value (and loop to the end if first element is matched ) based on first input found. if not found, returns first value of array
self[((self.index(value)||1)-1)%self.size]
end
end
arr1 = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
puts arr1.next("") #=> returns "Jan"
puts arr1.prev("") #=> returns "Jan"
puts arr1.next("Apr") #=> returns "May"
puts arr1.next("Dec") #=> returns "Jan"
puts arr1.prev("Jan") #=> returns "Dec"
puts arr1.prev("Apr") #=> returns "Mar"
Updated by Hanmac (Hans Mackowiak) almost 10 years ago
i think this functions might be interesting, but i would try to write them to that they are available in Enumerable too
Updated by nobu (Nobuyoshi Nakada) almost 10 years ago
- Description updated (diff)
An exception should be raised if the input is not found?
Updated by Hanmac (Hans Mackowiak) almost 10 years ago
i also would like if there are block variants of them like that
data = 0..10
data.prev_value {|o| o == 5} #=> 4
data.next_value {|o| o == 5} #=> 6
and i would use prev_value and next value instead of prev and next because it collide with Enumerator#next
i tryed to simulate such functions with slice_before and chunk, it did work but it was not very resource saving ..