【问题标题】:Assign a value to an attribute name为属性名称赋值
【发布时间】:2014-06-25 08:33:16
【问题描述】:

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

【问题讨论】:

  • 你有什么问题?
  • 如何给属性名赋值?感谢@Uri Agassi 和@DaveMongoose!

标签: ruby attributes assign


【解决方案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!

【讨论】:

  • 请添加所需的 ruby​​ 版本 :)
  • 只是为像我这样的新手提供的信息: (attr1: 1) => OK // (attr1 : 1) => ERROR
【解决方案2】:

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

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

【讨论】:

  • Hash#fetch 接受默认值,而不需要逻辑或运算符。无需在字符串插值内调用to_s,并且下划线命名法通常保留用于指示私有实例变量或方法,而不是方法参数(除非单独使用,在这种情况下它用于丢弃参数)。
猜你喜欢
  • 1970-01-01
  • 2016-07-29
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多