LoginSignup
1
0

More than 1 year has passed since last update.

RubyでPythonみたいな文字列スライスがしたい

Last updated at Posted at 2023-01-10

Pythonでは文字列sに対しs[a:b:n]とするとsa番目からb番目の1個手前までn個飛ばしで文字が取り出される。

一方Rubyの文字列クラスにもsliceメソッドがあり、

'abcdefg'.slice(1...5)

または

'abcdefg'[1...5]

はPythonの

'abcdefg'[1:5]

と同様であるが"n個飛ばし"はできない。

考えた強引なやり方

  • まずa番目からb番目の1個手前までの部分文字列を取り出す
  • 部分文字列からインデックス%n==0となる文字を取り出して繋げる(mapとjoinを使う)

例えばPythonでの'abcdefg'[1:5:3]はRubyでは以下のように書ける。

'abcdefg'[1...5].each_char.with_index.map { |c, idx| c if idx%3==0 }.join

idx%3==0(idx%3).zero?でも可。また、2つ飛ばしならidx.even?とも書ける。

別解

コメントEnumerator::ArithmeticSequenceを使った方法を教えていただきました。

str = 'abcdefg'
(1...5).step(3).map{ |i| str[i] }.join
1
0
2

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
1
0