Help us understand the problem. What is going on with this article?

Arrayにsplitがあって混乱した

次のようなコードを書いたところ、配列の配列が帰ってきて混乱しました。

numbers.split(/,/) #=> [["1","2","3"]]

原因は、split済みの配列に対してsplitを呼んでいたせいでした。

numbers = "1,2,3".split(/,/)
numbers.split(/,/) #=> [["1","2","3"]]

RailsのActiveSupportは Array#split を用意しています。特定の値の前後で配列を配列の配列に分割するものです。

[1, 2, 3, 4, 5].split(3) # => [[1,2],[4,5]]

しかし、変数に文字列が入っているつもりが配列だった、という場合には面食らうことなります。

def include_three?(string)
  string.split(/,/).include?("3")
end

include_three?("1,2,3,4,5".split(/,/)) #=> false
kazutosato
Railsプログラマー。リファクタリング、テスト書き、バージョンアップ、リプレースなどやっています。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした