I am wondering how one would search through an array of hashes and return a value based on a search string. For example, @contacts contains the hash elements: :full_name, :city, and :email. The variable @contacts (I guess it would be an array) contains three entries (perhaps rows). Below is the code I have so far to conduct a search based on :city value. However it’s not working. Can anyone give me an idea what’s going on?
def search string
@contacts.map {|hash| hash[:city] == string}
end
You should use
selectinstead ofmap:In your code you tried to
map(or transform) your array using a block, which yields boolean values.maptakes a block and invokes the block for each element ofself, constructing a new array containing elements returned by the block. As the result, you got an array of booleans.selectworks similar. It takes a block and iterates over the array as well, but instead of transforming the source array it returns an array containing elements for which the block returnstrue. So it’s a selection (or filtering) method.In order to understand the difference between these two methods it’s useful to see their example definitions:
Example usage: