0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby の slice が便利になった

Posted at

Python の

Python
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10][1:10:3]    #=>[2, 5, 8]

って便利ですよね。Ruby でこれをやろうとすると、ちょっと工夫が必要でした。

例えばこんな感じに。

Ruby
1.step(9, 3).map { [*1..10][_1] }    #=>[2, 5, 8]

しかし、これはいまでは(たぶん Ruby 3.0 から)こんな風に書けるようです。

s = (1...10).step(3)
s.class    #=>Enumerator::ArithmeticSequence
[*1..10].slice(s)    #=>[2, 5, 8]

これの応用で、%を使ってさらに短く書けます。

[*1..10].slice((1...10) % 3)   #=>[2, 5, 8]
[*1..10][(1...10) % 3]   #=>[2, 5, 8]

便利ですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?