在rails中创建新对象

问题描述 投票:3回答:3

我找不到一个很好的例子,所以请指出我正确的方向。

我想从头开始创建一个具有2个属性abbr和name的对象

我试图用50个状态和DC制作一个对象。由于我没有看到这个列表经常变化,我认为不需要数据库,也许我错了。

我试过以下没有成功:

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

我得到了undefined method abbr=' for #<Object:0x00000006763008>

我究竟做错了什么?

ruby object ruby-on-rails-3.1
3个回答
2
投票

你可以使用在YAML中读取/保持其状态/缩写/ i18n的decoder

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

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

4
投票

您可以创建一个没有数据库的简单类:

class State
  attr_accessor :abbr, :name
end

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

你的版本不起作用,因为Object没有abbr=name=方法,它不会在飞行中制作它们。


3
投票

Ruby中的对象与JavaScript中的对象完全不同,我认为你已经习惯了,因此动态添加属性并不是那么简单。 Hash,与JS中的关联数组非常相似,您可以将它用于您的目的:

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'

正如您所看到的,Hash提供了开箱即用的添加,查找和提取功能,因此您甚至无法定义自己的类。一旦你完成向状态添加状态,冻结内容也是一个好主意。

© www.soinside.com 2019 - 2024. All rights reserved.