# Regexp question

**URL:** <https://www.ruby-forum.com/t/regexp-question/109982>\
**Category:** Ruby\
**Created:** [July 20, 2007, 9:41pm UTC](https://www.ruby-forum.com/t/regexp-question/109982 "2007-07-20T21:41:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [July 20, 2007, 9:41pm UTC](https://www.ruby-forum.com/t/regexp-question/109982/1 "2007-07-20T21:41:08Z")

</div>

I have a list of zip codes (3000). Is there any script that I could  
use to create a regexp for checking if a user entered zip is in this  
list or not? TIA.

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [July 20, 2007, 10:24pm UTC](https://www.ruby-forum.com/t/regexp-question/109982/2 "2007-07-20T22:24:13Z")

</div>

quoth the removed\_email\_address@domain.invalid:

> I have a list of zip codes (3000). Is there any script that I could  
> use to create a regexp for checking if a user entered zip is in this  
> list or not? TIA.

Doubtful you need a regexp. Answer depends on the format of your list.  
If it  
is a separate file with one code per line you could do:

codes = IO.readlines("/path/to/codes").each { |line| line.chomp! }  
codes.include?(90210.to\_s)

or if you have ZIP + 4 codes:

codes.include?(“90210-1234”)

-d

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [July 20, 2007, 10:43pm UTC](https://www.ruby-forum.com/t/regexp-question/109982/3 "2007-07-20T22:43:15Z")

</div>

darren kirby wrote:

> codes = IO.readlines("/path/to/codes").each { |line| line.chomp! }  
> codes.include?(90210.to\_s)
> 
> or if you have ZIP + 4 codes:
> 
> codes.include?(“90210-1234”)
> 
> -d

Array#include? is slow for large arrays. If you’ll be performing more  
than 1 lookup over the life of the program, you should create a hash:

codes = Hash.new  
IO.readlines("/path/to/codes").each {|code| codes[code.chomp] = true}

Then just test with:  
codes[‘12345’]

Or you could use a Set, which basically does the exact same thing with  
different syntax:

require ‘set’  
codes = Set.new  
IO.readlines(’/path/to/codes").each {|code| set.add(code.chomp)}

Test with:  
set.include?(‘12345’)
