k,v

问题描述 投票:0回答:2

我希望能够通过getter和setter来添加和检索元素到哈希中。

class Config

  attr_reader :p1, :p2, :p4

  def initialize(options={})
    options.each do |k,v|
      instance_variable_set("@#{k}", v)
    end
  end

end

目前我只能添加和检索键为 p1, p2 and p3

如果我尝试添加新的元素,例如

> a = Config.new({name: "kevin"})
return value is
=> #<Config:0x000000000a4422a8 @name="kevin">

在试图访问名称

> a.name
NoMethodError: undefined method `name' for #<Config:0x000000000a4422a8 @name="kevin">

如何使用 a.name 以获得 "Kevin"

ruby hash attr-accessor
2个回答
© www.soinside.com 2019 - 2024. All rights reserved.