Generally in order to pick elements from array that match some specific conditione use select method.
select returns an array of all elements that matched critera or an empty list in case neither element has matched
example:
new_array = array.select do |element|
return_true_or_false_depending_on_element(element)
end
now when we would like to put every element in its own array we could you another array method that is available on array - map which takes every element of an array and transforms it in another element. In our case we will want to take every matching string and wrap it in array
map usage:
new_array = array.map do |element|
element_transformation(element) # in order to wrap element just return new array with element like this: [element]
end
coming back to your question. in order to verify whether a string starts with a letter you could use start_with? method which is available for every string
glueing it all together:
strings = ["apple", "banana", "animal", "car", "angel"]
result = strings.select do |string|
string.start_with?("a")
end.map do |string_that_start_with_a|
[string_that_start_with_a]
end
puts result
arr, return an array comprised of the those elements ofarrthat begin with"a", in the same order. The way it is now worded it sounds like you wish to create a new empty array, sayb, and then iterate overarr, executingb.push(string)(orb << string) when the elementstringofarrbegins with an"a". Do you see how that unnecessarily restricts the method of solution? @djaszczurowski's answer, for example, does not seem to meet your requirements but, imo, is the best answer.["apple"],["animal"],["angel"]is not an object. I assume you mean you wish to return an array. Do you want[["apple"], ["animal"], ["angel"]]or["apple", "animal", "angel"]? Some answers assume the former is wanted.