简体   繁体   中英

RoR - Find if part of a string matches an array of hashes

I know there are a lot of similar questions but I am struggling to find a specific answer.

i have an array of hashes with key of Symbol and a value of Price, I am looking to filter the array to only include the hashes that have a Symbol that ends in the letters ETL

Data looks like:

[ [
            {
                "symbol": "ABCDEF",
                "price": "4"
            },
            {
                "symbol": "GHIETL",
                "price": "5"
            }
        ]

You can use something like this:

array.select { |hash| hash[:symbol].end_with? "ETL" }

From the Ruby docs for select :

Returns an array containing all elements of enum for which the given block returns a true value.

You can also provide multiple suffixes to end_with? if you need to filter by multiple suffixes. For example:

array.select { |hash| hash[:symbol].end_with? "ETL", "DEF" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM