Area Codes

Hi! TOTAL noob question here but that’s what I am. I’m trying to create
a program where I type the area code, hit enter, and see it’s state. I
have a list of codes per state and it’s rather large. How’s the best way
to do this? I don’t want to use a database (MySQL) for this if that’s
possible. I’ve tried using if statements and hashes but didn’t know if
there’s a better way. I’ve searched for a gem that’s already written but
didn’t have any luck and I’ve googled to see if there’s source code for
this already but couldn’t find anything. Any ideas? Thanks!

Wood Y. wrote:

Hi! TOTAL noob question here but that’s what I am. I’m trying to create
a program where I type the area code, hit enter, and see it’s state. I
have a list of codes per state and it’s rather large. How’s the best way
to do this? I don’t want to use a database (MySQL) for this if that’s
possible. I’ve tried using if statements and hashes but didn’t know if
there’s a better way. I’ve searched for a gem that’s already written but
didn’t have any luck and I’ve googled to see if there’s source code for
this already but couldn’t find anything. Any ideas? Thanks!

Use a database (if this is a desktop application, SQLite would work
well; if you’re using JRuby, try H2). It’s the best way. If you use
one of the many excellent ORM libraries (ActiveRecord, Sequel,
DataMapper…), this is quite easy.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

On Feb 5, 2010, at 9:33 AM, Wood Y. wrote:

Hi! TOTAL noob question here but that’s what I am. I’m trying to create
a program where I type the area code, hit enter, and see it’s state. I
have a list of codes per state and it’s rather large. How’s the best way
to do this? I don’t want to use a database (MySQL) for this if that’s
possible. I’ve tried using if statements and hashes but didn’t know if
there’s a better way. I’ve searched for a gem that’s already written but
didn’t have any luck and I’ve googled to see if there’s source code for
this already but couldn’t find anything. Any ideas? Thanks!

There are lots of ways to do this. Maybe this script will give you
some ideas. This uses Ruby’s ability to embed data at the end of
the script but you could also store the data in an external file.

$ cat areacode.rb
BEGIN {
@info = {}
DATA.each_line do |x|
code, state = x.split
@info[code] = state
end
@state = Hash.new { |h,k| @info[k.to_s] }
}

[203,914,213].each { |c|
puts “area code #{c} is in #{@state[c]}”
}

Put your area code data below

END
203 CT
860 CT
914 NY
213 CA
$ ruby areacode.rb
area code 203 is in CT
area code 914 is in NY
area code 213 is in CA