w3resource

Ruby Array Exercises: Create a new array with the first element of two arrays

Ruby Array: Exercise-28 with Solution

Write a Ruby program to create a new array with the first element of two arrays. If lenght of any array is 0, ignore that array.

Ruby Array Exercises: Create a new array  with the first element of two arrays

Ruby Code:

def check_array(a, b)
    front = []
    if(a.length > 0 && b.length > 0)
        front[0] = a[0]
		front[1] = b[0]
    elsif (a.length > 0)
        front[0] = a[0]
    elsif (b.length > 0)
        front[0] = b[0]
    end
    return front
end

print check_array([3, 4, 5, 6], [7, 3, 4]),"\n"
print check_array([3, 4, 5], [6, 7, 3, 4, 7]),"\n"
print check_array([3, 4], [])  

Output:

[3, 7]
[3, 6]
[3]

Flowchart:

Flowchart: Create a new array  with the first element of two arrays

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to create a new array using first three elements of an given array of integers. If the length of the given array is less than three return the original array.
Next: Write a Ruby program to get the number of even integers in a given array.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.