为属性名称分配值

时间:2014-06-25 08:33:16

标签: ruby attributes assign

我想初始化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

2 个答案:

答案 0 :(得分: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!

答案 1 :(得分:-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