How to sensibly split an array around an object

来源:互联网 发布:sql数据类型转换 编辑:程序博客网 时间:2024/05/18 00:58

I have an array of uncertain length, let's say [1,2,3,4,5]. I want to subtract1 from everything before 3, and add 1 to everything after3, making the example [0,1,3,5,6]. If there is no 3, add 1 to everything: [1,2,4,5] => [2,3,5,6]. What is the most graceful way of doing this?

a = [1, 2, 3, 4, 5]n = a.index(3) || -1a.map.with_index{|e, i| e + (i <=> n)}# => [0, 1, 3, 5, 6]

0 0