3

I can't find a good example of this, so please point me in the right direction.

I want to create an object from scratch with 2 attributes abbr and name

I am trying to make an object with the 50 states and DC. Since I don't see this list changing every often, I don't see a need for a database, maybe I am wrong.

I have tried the following without success:

new_state = Object.new        
new_state.abbr = state[:abbr]     
new_state.name = state[:name]

and I get undefined method abbr=' for #<Object:0x00000006763008>

What am I doing wrong?

3 Answers 3

5

Object in Ruby is quite different from the one in JavaScript which I assume you got used to, so it's not that simple to add properties on the fly. Hash, instead is very similar to an associative array in JS, and you can use it for your purposes:

states = Hash.new # or just {}
states[state[:abbr]] = state[:name] # {'MD' => 'Maryland'}
states['AL'] = 'Alaska' # {'MD' => 'Maryland', 'AL' => 'Alaska'}
states.keys # => ['MD', 'AL']
states.values # => ['Maryland', 'Alaska']
states['AL'] # => 'Alaska'

As you can see, Hash provides adding, finding and fetching out of the box, so you don't even have do define your own class. It's also a good idea to .freeze the contents once you've done adding the states to it.

Sign up to request clarification or add additional context in comments.

Comments

5

You could create a simple class without a database behind it:

class State
  attr_accessor :abbr, :name
end

new_state = State.new
new_state.abbr = state[:abbr]
new_state.name = state[:name]

Your version doesn't work because Object doesn't have abbr= or name= methods and it won't make them up on the fly.

1 Comment

As always, your comment was awesome. I just think the other way will be a better solution for me.
2

you can use decoder that reads from/keeps its states/abbreviations/i18n in YAML.

Decoder.i18n = :en
country = Decoder::Countries[:US]
country.to_s
# => "United States"    

state = country[:MA]
state.to_s
# => "Massachusetts"

2 Comments

This is great, now is there one that does vehicle makes and models? haha
there was an attempt to use KBB APIs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.