Rails beginner
Rails beginner

Reputation: 14504

Ruby how to remove [] brackets from array?

I have this array:

[[16], [14], [13], [17], [18], [15, 16], [15, 14], [15, 13], [15, 17], [15, 18], [16, 14], [16, 13], [16, 17], [16, 18], [14, 13], [14, 17], [14, 18], [13, 17], [13, 18], [17, 18], [15, 16, 14], [15, 16, 13], [15, 16, 17], [15, 16, 18], [15, 14, 13], [15, 14, 17], [15, 14, 18], [15, 13, 17], [15, 13, 18], [15, 17, 18], [16, 14, 13], [16, 14, 17], [16, 14, 18], [16, 13, 17], [16, 13, 18], [16, 17, 18], [14, 13, 17], [14, 13, 18], [14, 17, 18]]

How do I remove some array brackets [] so that the array would be like:

[16, 14, 13, 17, 18, [15, 16], ..., [14, 13, 18], [14, 17, 18]]

Upvotes: 0

Views: 3212

Answers (3)

Dave Newton
Dave Newton

Reputation: 160171

new_arr = arr.collect { |a| a.size == 1 ? a[0] : a }

Or, in-place:

arr.collect! { |a| a.size == 1 ? a[0] : a }

Output for non-believers:

[1] pry(main)> arr = [[16], [14], [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]
=> [[16], [14], [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]
[3] pry(main)> new_arr = arr.collect { |a| a.size == 1 ? a[0] : a }
=> [16, 14, [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]
# Note that arr is unchanged at this point.
[5] pry(main)> arr.collect! { |a| a.size == 1 ? a[0] : a }
=> [16, 14, [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]
[6] pry(main)> arr
=> [16, 14, [15, 16], [15, 14], [15, 16, 17], [15, 16, 18]]

Upvotes: 3

t0d0r
t0d0r

Reputation: 48

this is not very elegant, but you will got what you want :)

b = [[16], [14], [13], [17], [18], [15, 16], [15, 14], [15, 13], [15, 17], [15, 18], [16, 14], [16, 13], [16, 17], [16, 18], [14, 13], [14, 17], [14, 18], [13, 17], [13, 18], [17, 18], [15, 16, 14], [15, 16, 13], [15, 16, 17], [15, 16, 18], [15, 14, 13], [15, 14, 17], [15, 14, 18], [15, 13, 17], [15, 13, 18], [15, 17, 18], [16, 14, 13], [16, 14, 17], [16, 14, 18], [16, 13, 17], [16, 13, 18], [16, 17, 18], [14, 13, 17], [14, 13, 18], [14, 17, 18]]

b.collect { |c| c.count() ==  1 ? c[0] : c }

Upvotes: 1

varatis
varatis

Reputation: 14740

This question is kind of unclear. It seems you have an array of arrays, yes? If so, you can do something like this

count = 0
array.each { |x|
  if x.is_a?(Array)
    if x.length == 1
      array[count] = x[0]
    end
  end
  count = count + 1
}

This could be made a little prettier, but it should do what you want, if what you want is to swap a single element array for just an integer. I'm not entirely sure if you can do this in Ruby, however - have an array that is an array of integers and arrays - but I think you can (you couldn't do something like this in Java).

Upvotes: 0

Related Questions