I'm trying to understand how grep works in this example. The code works but I'm not 100% sure in what sequence the events take place or whether I'm correctly understanding what's being returned when and where.
cars = [:Ford, :Toyota, :Audi, :Honda]
ucased_cars = cars.collect do |c|
c.to_s
end
.grep(/^Ford/) do |car|
puts car.upcase
car.upcase
end
puts "ucased:" + ucased_cars.to_s
What I think is happening is:
- I define an array of Symbols
- I call the collect method with a block which causes each Symbol element, c, of the cars array to be converted into a String inside the block.
- collect returns an array of Strings
- grep is invoked on the array of Strings returned by collect and grep calls its own block on each array element, car, matching the search pattern, causing the element to be printed, uppercased and returned as part of an array.
- grep returns an array of uppercased Strings, assigning it to 'ucased_cars'
- The array, ucased_cars, must be converted to a String before being printed.
As far as step #4 is concerned, which of the following best describes how grep works:
[A] grep finds all strings matching the pattern. grep calls the block on this array of matches. grep returns the results of the block to the invoking function.
[B] grep finds the first string matching the pattern. grep calls the block on this match. this block's return value is piled up somewhere temporarily. grep searches the next element of the array. if it matches, grep calls the block on this match. grep adds this block's return value to the temporary "storage" of return values. grep looks at the next array element until it finds no more matches. then grep passes the stacked up return values back to the invoking function.
My Conclusion:
[A] seems to make more sense.
[B] seems like a lot of unnecessary fudging and does't seem efficient or likely.