当前位置 : 主页 > 编程语言 > ruby >

如何在Ruby中实现查找类?

来源:互联网 收集:自由互联 发布时间:2021-06-23
我有一个不可变值对象列表. lookup类提供了迭代和查询数据的方法: class Banker Bank = Struct.new(:name, :bic, :codes) attr_reader :banks def initialize @banks = [ Bank.new('Citibank', '1234567', ['1', '2']), Bank.new
我有一个不可变值对象列表. lookup类提供了迭代和查询数据的方法:

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.有哪些选项可以缓存@banks,以便它可以在Banker的不同实例中重复使用?

我不认为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.class中的self是区分self类和关键字class所必需的.

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

并删除初始化中的第一行.

或者,如果你有一个完整的所有银行列表,你可以改为使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值.

网友评论