w3resource

Ruby Array Exercises: Search items start with specified string of a given array

Ruby Array: Exercise-45 with Solution

Write a Ruby program to search items start with specified string of a given array.

Ruby Array Exercises: Search items start with specified string of a given array

Ruby Code:

arra1 = ['abcde', 'abdf', 'adeab', 'abdgse', 'bdefa', 'bacdef']
print "Original array:\n"
print arra1
print "\nSearch items start with 'ab':\n"
print arra1.grep(/^ab/)
print "\nSearch items start with 'b':\n"
print arra1.grep(/^b/)

Output:

Original array:
["abcde", "abdf", "adeab", "abdgse", "bdefa", "bacdef"]
Search items start with 'ab':
["abcde", "abdf", "abdgse"]
Search items start with 'b':
["bdefa", "bacdef"]

Flowchart:

Flowchart: Search items start with specified string of a given array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check whether all items are identical in a given array.
Next: Write a Ruby program to iterate an array starting from the last element.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/ruby-exercises/array/ruby-array-exercise-45.php