LoginSignup
1
0

More than 3 years have passed since last update.

Arrayにsplitがあって混乱した

Last updated at Posted at 2020-07-13

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

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