根据其他实例变量值创建 Ruby 个实例变量作为默认值

Create Ruby instance variable to default based off of other instance variable values

我正在创建一个将散列作为参数的 Ruby class:

class Player
include PlayerHelper
attr_accessor :at_bats, :hits, :walks, :hbp, :sac_flies, :singles, :doubles,
              :triples, :hr, :put_outs, :assists, :errors, :er, :ip, :so,
              :stolen_bases, :caught_stealing
def initialize(hash)
  @at_bats = hash.fetch(:at_bats, nil)
  @hits = hash.fetch(:hits, nil)
  @walks = hash.fetch(:walks, nil)
  @hbp = hash.fetch(:hbp, nil)
  @sac_flies = hash.fetch(:sac_flies, nil)
  @singles = hash.fetch(:singles, nil)
  @doubles = hash.fetch(:doubles, nil)
  @triples = hash.fetch(:triples, nil)
  @hr = hash.fetch(:hr, nil)
  @put_outs = hash.fetch(:put_outs, nil)
  @assists = hash.fetch(:assists, nil)
  @errors = hash.fetch(:errors, nil)
  @er = hash.fetch(:er, nil)
  @ip = hash.fetch(:ip, nil)
  @walks = hash.fetch(:walks, nil)
  @hits = hash.fetch(:hits, nil)
  @so = hash.fetch(:so, nil)
  @stolen_bases = hash.fetch(:stolen_bases, nil)
  @caught_stealing = hash.fetch(:caught_stealing, nil)
end

我想为用户提供包含 :singles 的选项,并首先检查 :singles 是否包含在哈希中。如果是这样,给它散列值。这部分我正在处理。

如果 :singles 键不存在,我无法开始工作的是给@singles :hits - (:doubles + :triples + :hr) 的值。我试过制作一个单独的方法来最初调用,但这似乎不起作用。

如果不包含 :singles 密钥,我如何根据其他哈希值设置 @singles 的值?

使用 ||=,它是 neu = neu || old 的语法糖,当且仅当它之前没有设置时才设置新值(等于 nil。)

ALL = %i[
  at_bats hits walks hbp sac_flies singles
  doubles triples hr put_outs assists errors
  er ip so stolen_bases caught_stealing
]

attr_accessor *ALL

def initialize(hash) do
  ALL.each do |iv|
    instance_variable_set("@{iv}", hash.fetch(iv, nil))
  end

  #        ⇓⇓⇓ set if and only it was not set previously 
  @singles ||= @hits - (@doubles + @triples + @hr)
end

这就是 fetch 方法的第二个参数的用途:

def initialize(hash)
  # ...
  @hits = hash.fetch(:hits, nil)
  @doubles = hash.fetch(:doubles, nil)
  @triples = hash.fetch(:triples, nil)
  @hr = hash.fetch(:hr, nil)
  @singles = hash.fetch(:singles, @hits - (@doubles + @tripples + @hr))
  # ...
end

但是,请注意,由于您将所有值默认为 nil,如果这些值未传递到构造函数中,您可能会遇到 undefined method on nil:NilClass 类型的错误!您可能希望设置一些不同的默认值,或使它们成为必需的参数...