shuba.ivan shuba.ivan - 1 year ago 161
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 Source

No need loop it twice.

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

a.flatten.each {|x| puts x if x>0}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download