在 Ruby 中初始化对象时如何设置属性值? [英] How can one set property values when initializing an object in Ruby?

查看:47
本文介绍了在 Ruby 中初始化对象时如何设置属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类:

class Test
  attr_accessor :name
end

创建对象时,我想执行以下操作:

When I create the object, I want to do the following:

t = Test.new {name = 'Some Test Object'}

目前,它导致 name 属性仍然是 nil.

At the moment, it results in the name attribute still being nil.

可以不添加初始化器吗?

Is that possible without adding an initializer?

推荐答案

ok,

我想出了一个解决方案.它使用 initialize 方法,但另一方面,它完全符合您的要求.

I came up with a solution. It uses the initialize method but on the other hand do exactly what you want.

class Test
  attr_accessor :name

  def initialize(init)
    init.each_pair do |key, val|
      instance_variable_set('@' + key.to_s, val)
    end
  end

  def display
    puts @name
  end

end

t = Test.new :name => 'hello'
t.display

开心吗?:)

使用继承的替代解决方案.请注意,使用此解决方案,您无需显式声明 attr_accessor!

Alternative solution using inheritance. Note, with this solution, you don't need to explicitly declare the attr_accessor!

class CSharpStyle
  def initialize(init)
    init.each_pair do |key, val|
      instance_variable_set('@' + key.to_s, val)
      instance_eval "class << self; attr_accessor :#{key.to_s}; end"
    end
  end
end

class Test < CSharpStyle
  def initialize(arg1, arg2, *init)
    super(init.last)
  end
end

t = Test.new 'a val 1', 'a val 2', {:left => 'gauche', :right => 'droite'}
puts "#{t.left} <=> #{t.right}"

这篇关于在 Ruby 中初始化对象时如何设置属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆