Replace a long case statement involving regex with a hash

1 week ago 10
ARTICLE AD BOX

You are using a string as a key in your hash map instead of a regular expression object.
Here is the correct hash map declaration:

file_types = { /camt.053.001/ => 'camt053', /camt.052.001/ => 'camt052', /"Auftragskonto";"Buchungstag";"Valutadatum";/ => 'SpK' }

Jupit90's user avatar

I would use a single regex and a hash code that does not use regex, just the output of a
single regex match to do the code lookup.

Demo : https://www.jdoodle.com/ia/1NBq

file_types = { 'camt.053.001' => 'camt053', 'camt.052.001' => 'camt052', '"Auftragskonto";"Buchungstag";"Valutadatum";' => 'SpK' } RxFileTypes = /(?:camt\.053\.001|camt\.052\.001\.08|"Auftragskonto";"Buchungstag";"Valutadatum";)/ first_bytes = '<?xml version="1.0" encoding="UTF-8"?><Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02"' match = first_bytes.match( RxFileTypes ) if match puts "File type code is : " + file_types[ match[0] ] end

Output

File type code is : camt053

Combine all the file types into a single regex separated by alternations.
The match will be the Key into the File Type code hash.

(?: camt \. 053 \. 001 | camt \. 052 \. 001 \. 08 | "Auftragskonto";"Buchungstag";"Valutadatum"; )

For additional File types just add another alternation and an entry into the File Type code hash.

sln's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article