David Vallner
10/20/2006 12:52:00 AM
khaines@enigo.com wrote:
> If one has a list of en, en-gb and es, and one gets an Accept-Language
> header like this:
>
> es-mx,es;q=0.8,en-us;q=0.5,en;q=0.3
>
> the code would return the 'es' as the best matching language option.
>
I have some doubts you'll ever see that sort of header in the wild.
Besides, parsing that one is hardly something that needs a C library.
Here's an almost-one-liner, if you're willing to forgive the each block
being three statements and remove all whitespace (it actually parses...)
"es-mx,es;q=0.8,en-us;q=0.5,en;q=0.3".split(",").map { | i |
i.split(";")
}.each { | i |
i[1] =~ /q=(\d+\.\d+)/;
i[1] = $1 && $1.to_f || 1.0
}.sort_by{ | i |
i[1]
}.reverse[0][0]
=> "es-mx"
(The quality value for es-mx defaults to 1, es is only 0.8)
David Vallner
(That's by far the ugliest code I've written in a year.)