Toby Joiner
Toby Joiner

Reputation: 4376

create new object in rails

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?

Upvotes: 3

Views: 27490

Answers (3)

mu is too short
mu is too short

Reputation: 434585

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.

Upvotes: 5

phil pirozhkov
phil pirozhkov

Reputation: 4900

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.

Upvotes: 5

tolitius
tolitius

Reputation: 22499

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"

Upvotes: 2

Related Questions