/ Published in: Ruby
Public domain. Only works for integers. Passing update_array as "true" will return the original array with the new value inserted in the appropriate position; ignoring update_array will return the index at which the new value should be inserted.
Expand |
Embed | Plain Text
def insert_value_in_order(array_of_values, new_value, update_array = nil) value_index = array_of_values.index(new_value) index = 0 if !value_index && array_of_values.last.to_i > new_value i = 0 while array_of_values[i].to_i < new_value do i += 1 end index = i else index = value_index ? value_index : -1 end return update_array == true || update_array == 1 ? array_of_values.insert(index, new_value) : index end
You need to login to post a comment.
