Ruby Array Exercises: Create a new array with the first element of two arrays
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 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:
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics