In your #inject
block, you passed last entry as "5,6"
. Now inside the if
block, you splitted it to an array. Then you called the method #each
on [5,6]
. Now #each
method returns the receiver on which you called it.
But in the second case, you called t.each
at the last of each iteration of the inject
block. So on the final pass t
is a complete array [1,2,3,4,5,6]
. Now as I said, Array#each
returns the receiver, so you got the full t
back , that [1,2,3,4,5,6]
.
I would write your code as :
ary = ["1,2,3","4","5,6"]
ary.flat_map { |str| str.include?(",") ? str.split(',') : str }
# => ["1", "2", "3", "4", "5", "6"]
If you want to use #inject
do :
ary = ["1,2,3","4","5,6"]
ary.inject([]) { |a,str| a.concat(str.split(',')) }
# => ["1", "2", "3", "4", "5", "6"]