为属性名称分配值

问题描述 投票:-1回答:2

我想初始化attr3='c',属性的数量可以改变。

class MyClass
    attr_accessor :attr1, :attr2, :attr3
    def initialize(attr1 = 1, attr2 = 2, attr3 = 3)
         @attr1 = attr1
         @attr2 = attr2
         @attr3 = attr3
    end
end

myclass = MyClass.new
myclass.attr1 # => 1
myclass.attr2 # => 2
myclass.attr3 # => 3

myclass = MyClass.new('c')
myclass.attr1 # => c
myclass.attr2 # => 2
myclass.attr3 # => 3

我试图为属性名称赋值。

myclass = MyClass.new({attr3 : 'c'}) # => but that doesn't work
ruby attributes assign
2个回答
-1
投票

编写初始化程序以获取哈希值:

def initialize(attributes = {})
  # If the attributes hash doesn't have the relevant key, set it to default:
  @attr1 = attributes.fetch(:attr1, 1)
  @attr2 = attributes.fetch(:attr2, 2)
  @attr3 = attributes.fetch(:attr3, 3)
end

对于更通用的解决方案,您可以遍历哈希中的键:

def initialize(attributes = {})
  attributes.each do |key, value|
    send("#{key}=", value) if respond_to?("#{key}=")
  end
end

1
投票

要使用命名默认值(假设您使用Ruby 2.0 and up):

def initialize(attr1: 1, attr2: 2, attr3: 3)
     @attr1 = attr1
     @attr2 = attr2
     @attr3 = attr3
end

请注意,此方法不能与前一个方法一起使用:

myclass = MyClass.new
myclass.attr1 # => 1
myclass.attr2 # => 2
myclass.attr3 # => 3

myclass = MyClass.new(attr1: 'c')
myclass.attr1 # => c
myclass.attr2 # => 2
myclass.attr3 # => 3

myclass = MyClass.new('c') # ERROR!
© www.soinside.com 2019 - 2024. All rights reserved.