简体   繁体   English

如何在ruby中将整数分为对偶部分

[英]How can I separate integers as dual parts in ruby

I have defined an array: 我定义了一个数组:

years = (2014..Time.now.year + 1).to_a
#=> [2014, 2015, 2016, 2017, 2018]

I want to show an output like this: 我想显示这样的输出:

['2014-2015', '2015-2016', '2016-2017', '2017-2018']

Do you have any good advice? 您有什么好的建议吗?

Enumerable#each_cons Enumerable#each_cons

Iterates the given block for each array of consecutive elements. 为每个连续元素数组迭代给定的块。

(2014..Time.now.year + 1).each_cons(2).to_a # => [[2014, 2015], [2015, 2016], [2016, 2017], [2017, 2018]]

I believe you can handle the rest. 我相信您可以解决剩下的一切。

No need to reinvent the wheel, just use map : 无需重新发明轮子,只需使用map

(2014..Time.now.year).map { |year| "#{year}-#{year + 1}" } 
#=> ["2014-2015", "2015-2016", "2016-2017", "2017-2018"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM