41
29

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 5 years have passed since last update.

文字列を指定した文字数ごとに分割する。RubyとPythonで。

Last updated at Posted at 2015-08-28

はからずも最近Rubyを書いていて、Rubyだとこうかけるの知った

test.rb
s = '123456789'
v = s.each_char.each_slice(3).map(&:join)
# ['123', '456', '789']

かっこいい〜

Pythonだとこうでしょうか

test.py
s = '123456789'
v = [s[i: i+3] for i in range(0, len(s), 3)]
# ['123', '456', '789']

どっちがいいかと言われたら、個人的にはリスト内包表記とか汎用的な仕組みの組み合わせで出来るPythonのほうが好みだけど、 Rubyのほうが何してるかわかりやすい。いちいちメソッドがあるのすごい。

41
29
4

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
41
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?