简体   繁体   中英

Ruby : Find a Date in a array of strings

I am searching through an array of strings looking for a Date :

Is the method I'm using a good way to do it? OR . . . is there a better alternative.

Perhaps a more "beautiful" way to do it?

    query = {'Hvaða','mánaðardagur','er','í','dag?','Það','er','02.06.2011','hví','spyrðu?'}

    def has_date(query)
        date = nil
        query.each do |q|
            begin
                date = Date.parse(q)
                query.delete(q)
                break
            rescue
            end
       end
       return date
    end

Note that in Ruby we use square brackets [] for array literals (curly braces {} are for Hash literals).

Here is a solution that will find all dates in the array and return them as strings (thanks @steenslag):

require 'date'
arr = ['Hvaða', 'er', '02.06.2011', 'hví', '2011-01-01', '???']
dates = arr.select { |x| Date.parse(x) rescue nil }
dates # => ["02.06.2011", "2011-01-01"]

First you can try to validate the string, if it's a valid date format then you can parse it as a date:

query.each do |item|
  if item =~ /^\d{2}([-\\\/.])\d{2}\1\d{4}$/ then
    # coding
  end
end

If you just want the first date and you want to be strict about a valid date:

arr = ['Hvaða', 'er', '02.06.2011', 'hví', '2011-01-01', '???']

date = arr.detect do |x|  ## or find
  d,m,y = x.split('.')
  Date.valid_civil?(y.to_i, m.to_i, d.to_i)
end

p date #=> "02.06.2011"

(Date.parse is forgiving, it happily parses 02.13.2011)

If you want to parse more types of dates, use Chronic ... I think it also has the side effect of not raising errors, just returns nil.

So if you want all valid dates found:

arr = ['Hvaða', 'er', '02.06.2011', 'hví', '2011-01-01', '???']
arr.collect {|a| Chronic.parse a}.compact

If you want the first:

arr.find {|a| Chronic.parse a}

and if you just want a true/false "is there a date here?"

arr.any? {|a| Chronic.parse a}

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