3

我有一个不可变值对象的列表。查找类提供了迭代和查询该数据的方法:

class Banker
  Bank = Struct.new(:name, :bic, :codes)

  attr_reader :banks
  def initialize
    @banks = [
      Bank.new('Citibank',    '1234567', ['1', '2']),
      Bank.new('Wells Fargo', '7654321', ['4']), # etc.
    ]
  end

  def find_by_bic(bic)
    banks.each do |bank|
      return bank if bank.bic == bic
    end
  end
end

@banks每次Banker使用时都会被初始化。有哪些选项可以缓存@banks,以便在 ? 的不同实例中重复使用Banker

4

2 回答 2

4

我不认为Struct在这里给你买任何东西。这样做怎么样?

代码

class Banker
  @all_banks = {}

  class << self
    attr_reader :all_banks
  end

  attr_reader :banks

  def initialize(banks)
    @banks = banks.keys
    banks.each { |k,v| self.class.all_banks[k] = v }
  end

  def find_by_bic(bic)
    return nil unless @banks.include?(bic)
    self.class.all_banks[bic]
  end
end

需要注意区分关键字self的类。self.classselfclass

例子

b1 = Banker.new({ '1234567' => { name: 'Citibank', codes: ["1", "2"] },
                  '7654321' => { name: 'Wells Fargo', codes: ['4'] } })
b1.banks
  #=> ["1234567", "7654321"]
Banker.all_banks
  #=> {"1234567"=>{:name=>"Citibank", :codes=>["1", "2"]},
  #    "7654321"=>{:name=>"Wells Fargo", :codes=>["4"]}}
b1.find_by_bic '7654321'
  #=> {:name=>"Wells Fargo", :codes=>["4"]}
b1.find_by_bic '1234567'
  #=> {:name=>"Citibank", :codes=>["1", "2"]}
b1.find_by_bic '0000000'
  #=> nil

b2 = Banker.new({ '6523155' => { name: 'Bank of America', codes: ["3"] },
                  '1234567' => { name: 'Citibank', codes: ["1", "2"] } })
b2.banks
  #=> ["6523155", "1234567"]
Banker.all_banks
  #=> {"1234567"=>{:name=>"Citibank", :codes=>["1", "2"]},
  #    "7654321"=>{:name=>"Wells Fargo", :codes=>["4"]},
  #    "6523155"=>{:name=>"Bank of America", :codes=>["3"]}}
b2.find_by_bic '6523155'
  #=> {:name=>"Bank of America", :codes=>["3"]}
b2.find_by_bic '1234567'
  #=> {:name=>"Citibank", :codes=>["1", "2"]}
b2.find_by_bic '7654321'
  #=> nil

备择方案

如果您愿意,可以改为添加类方法:

def self.new(banks)
  banks.each { |k,v| all_banks[k] = v }
  super
 end

并删除initialize.

或者,如果您有所有银行的完整列表,则可以改为创建all_banks一个常量:

ALL_BANKS = {"1234567"=>{:name=>"Citibank", :codes=>["1", "2"]},
             "7654321"=>{:name=>"Wells Fargo", :codes=>["4"]},
             "6523155"=>{:name=>"Bank of America", :codes=>["3"]}}

def find_by_bic(bic)
  return nil unless @banks.include?(bic)
  ALL_BANKS[bic]
end

并更改initialize为:

def initialize(bics)
  @banks = bics
end

其中bics是一个bic值数组。

于 2014-10-12T19:25:00.943 回答
3

要在实例之间共享不可变数据,您可以使用冻结类变量:@@banks ||= [...].freeze

于 2014-10-12T13:25:52.793 回答