shuba.ivan shuba.ivan - 6 months ago 11
Ruby Question

Ruby random array

I have created a two-dimensional (

4x4
) array, where each element is a random number from
-10
to
10
.

I would like to now print all negative elements of this array in the terminal. How can one do this?

Here is my code so far which initialises the array, along with my current attempt to print all negative values:

a = Array.new(4) { rand(-10...10) }

a[0] = Array.new(4) { rand(-10...10) }
a[1] = Array.new(4) { rand(-10...10) }
a[2] = Array.new(4) { rand(-10...10) }
a[3] = Array.new(4) { rand(-10...10) }

a.each {|i|
a.each {|j|
puts j
}
}

Answer

No need loop it twice.

a = Array.new(4) { Array.new(4) { rand(-10..10) } }

a.flatten.each {|x| puts x if x>0}
Comments