基于其他实例变量值将Ruby实例变量创建为默认值

时间:2018-04-10 10:40:13

标签: ruby instance-variables

我正在创建一个以哈希为参数的Ruby类:

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键不存在,我可以开始工作的是给:hits - (:doubles + :triples + :hr) singles的值。@singles我尝试过最初调用一个单独的方法,但这似乎不起作用。

如果没有包含:singles密钥,如何根据其他哈希值设置let string = """ 1). \n\nRanjitha, 20\n\n\"N0? yE¥ WQRKINQ Il. iM gm N-LI?\']\" ......\n\nYou\'ve crossed paths 10 times\n\nPoth btDtlun\n\n 2).\n\nShruthi, 21\n\n 3).\n\nKhushbu,22\n©\n\n 4). \n\nVanitha, 22 \'r-e\'\"\n\nC? Bishop Cotton Women‘s Christian College\n\n® 5 kilometres away\n\n """ let pattern = "(\\w+),\\s?(\\d+)" do { let regex = try NSRegularExpression(pattern: pattern) let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string)) for match in matches { let nameRange = Range(match.range(at: 1), in: string)! print("name", string[nameRange]) let ageRange = Range(match.range(at: 2), in: string)! print("age", string[ageRange]) } } catch { print("Regex Error:", error) } 的值?

2 个答案:

答案 0 :(得分:1)

使用||=这是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

答案 1 :(得分:1)

这就是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 - 类型错误!您可能希望设置一些不同的默认值,或者使它们成为必需的参数......

相关问题