我有我的目标国家的阵列,其具有的属性“代码”和“名”红宝石阵列的UNIQ无法工作
该阵列可以有一个国家在它不止一次,所以我想不同的阵列。
这是我的国家类
class Country
include Mongoid::Fields::Serializable
attr_accessor :name, :code
FILTERS = ["Afghanistan","Brunei","Iran", "Kuwait", "Libya", "Saudi Arabia", "Sudan", "Yemen", "Britain (UK)", "Antarctica", "Bonaire Sint Eustatius & Saba", "British Indian Ocean Territory", "Cocos (Keeling) Islands", "St Barthelemy", "St Martin (French part)", "Svalbard & Jan Mayen","Vatican City"]
EXTRAS = {
'eng' => 'England',
'wal' => 'Wales',
'sco' => 'Scotland',
'nlr' => 'Northern Ireland'
}
def initialize(name, code)
@name = name
@code = code
end
def deserialize(object)
return nil unless object
Country.new(object['name'], object['code'])
end
def serialize(country)
{:name => country.name, :code => country.code}
end
def self.all
add_extras(filter(TZInfo::Country.all.map{|country| to_country country})).sort! {|c1, c2| c1.name <=> c2.name}
end
def self.get(code)
begin
to_country TZInfo::Country.get(code)
rescue TZInfo::InvalidCountryCode => e
'InvalidCountryCode' unless EXTRAS.has_key? code
Country.new EXTRAS[code], code
end
end
def self.get_by_name(name)
all.select {|country| country.name.downcase == name.downcase}.first
end
def self.filter(countries)
countries.reject {|country| FILTERS.include?(country.name)}
end
def self.add_extras(countries)
countries + EXTRAS.map{|k,v| Country.new v, k}
end
private
def self.to_country(country)
Country.new country.name, country.code
end
end
和我的阵列请求从另一类
def countries_ive_drunk
(had_drinks.map {|drink| drink.beer.country }).uniq
end
如果我把数组我能看到的结构称为是:
[
#<Country:0x5e3b4c8 @name="Belarus", @code="BY">,
#<Country:0x5e396e0 @name="Britain (UK)", @code="GB">,
#<Country:0x5e3f350 @name="Czech Republic", @code="CZ">,
#<Country:0x5e3d730 @name="Germany", @code="DE">,
#<Country:0x5e43778 @name="United States", @code="US">,
#<Country:0x5e42398 @name="England", @code="eng">,
#<Country:0x5e40f70 @name="Aaland Islands", @code="AX">,
#<Country:0x5e47978 @name="England", @code="eng">,
#<Country:0x5e46358 @name="Portugal", @code="PT">,
#<Country:0x5e44d38 @name="Georgia", @code="GE">,
#<Country:0x5e4b668 @name="Germany", @code="DE">,
#<Country:0x5e4a2a0 @name="Anguilla", @code="AI">,
#<Country:0x5e48c98 @name="Anguilla", @code="AI">
]
这是一样的,不管我是否做.uniq,你可以看到有两个“安圭拉”
与你的问题没有关系,但'serialize'和'deserialize'可能应该是singleton方法而不是实例方法,不是? – 2012-01-08 18:16:10