1
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 1 year has passed since last update.

【初心者向け】Ruby のまずいコード 25 本Advent Calendar 2021

Day 3

【Ruby のまずいコード】文字列を文字の配列にする

Last updated at Posted at 2021-12-02

お題

文字列(例えば "Ruby")を文字の配列(["R", "u", "b" ,"y"])に変換してください。

コード

str = "Ruby"

chars = str.split("")

改善

このコードはとくにまずいということはないと思いますが,この目的には専用のメソッド String#chars があるので,それを使えばいいでしょう。

str = "Ruby"

chars = str.chars

速度面では変わらないようです。
chars のメリットは簡潔なことですが,意図が分かりやすいとは言えるかと思います。
String#split の仕様はかなり複雑で,筆者もその全ては記憶していません。たとえば,以下のコードで,結果をすべて正確に言えますか?(私は怪しいです)

str = "  A  B  "

p str.split      # => ["A", "B"]
p str.split("")  # => [" ", " ", "A", " ", " ", "B", " ", " "]
p str.split(" ") # => ["A", "B"]
p str.split(nil) # => ["A", "B"]
$; = "A"
p str.split      # => ["  ", "  B  "]
p str.split(nil) # => ["  ", "  B  "]
1
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
1
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?