user25959
user25959

Reputation: 130

One-step flattening of an array in ruby

I am working out this exercise in codewars, which is to flatten an array (up to one-level deep) so for example, I want to get the outputs:

[1,2,3] >> [1,2,3]

[[1,2],3] >> [1,2,3]

[[1,[2]],3] >> [1,[2],3]

I decided to use "inject" - where the next element gets added to the running total if that element is an array, or just pushed if it is not:

def flatten(array)
  array.inject([]) {|result,element| element.kind_of?(Array) result.concat(element) : result<<element}
end

Could anyone help explain why I am getting the following syntax error?

-e:3: syntax error, unexpected tIDENTIFIER, expecting '}'
... element.kind_of?(Array) result.concat(element) : result<

Upvotes: 2

Views: 1781

Answers (1)

Ilya
Ilya

Reputation: 13477

You got an error cause you missed a ? in ternary statement:

element.kind_of?(Array) ? result.concat(element) : result<<element

For your goal you can use Array#flatten with an argument:

array.flatten(1)
[[1,2],3].flatten(1)
=> [1, 2, 3]
[[1,[2]],3].flatten(1)
=> [1, [2], 3]

Upvotes: 7

Related Questions