加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby数组一次访问2个连续(链接)元素

发布时间:2020-12-16 20:44:13 所属栏目:百科 来源:网络整理
导读:现在,这是数组, [1,2,3,4,5,6,7,8,9] 我想要, [1,2],[2,3],[3,4] upto [8,9] 当我做,每个人(2)我得到, [[1,4]..[8,9]] 我目前这样做, arr.each_with_index do |i,j| p [i,arr[j+1]].compact #During your arr.size is a odd number,remove nil.end 有没有更
现在,这是数组,
[1,2,3,4,5,6,7,8,9]

我想要,

[1,2],[2,3],[3,4] upto [8,9]

当我做,每个人(2)我得到,

[[1,4]..[8,9]]

我目前这样做,

arr.each_with_index do |i,j|
  p [i,arr[j+1]].compact #During your arr.size is a odd number,remove nil.
end

有没有更好的办法??

解决方法

Ruby读了你的头脑.你想要隐性的元素?
[1,9].each_cons(2).to_a
# => [[1,4],[4,5],[5,6],[6,7],[7,8],[8,9]]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读