【问题标题】:Passing object properties to function call in Ruby class将对象属性传递给Ruby类中的函数调用
【发布时间】:2018-08-17 05:07:34
【问题描述】:
def printer_outside_class(value)
 puts value
end

class Prints
 attr_accessor :value
 def initialize(a)
   @value = a
 end
 printer_outside_class(@value)
end 

Prints.new(100)

我没有得到任何输出,而是抛出警告“实例变量@value 未初始化”。 Ruby 逐行执行类,所以在调用initialize 函数之前,printer_outside_class(value) 被调用。

是否有可能以某种方式将变量value 传递给外部printer_outside_class(@value) 函数调用? value 应该从外部传递,不需要通过构造函数。

注意:我可以随意更改构造函数,向Prints 类添加任意代码,添加一个新类并可以随意调用Prints 类。但是,我将无法在函数定义中移动函数调用 printer_outside_class(@value)

【问题讨论】:

    标签: ruby class


    【解决方案1】:

    如果我正确理解了这个问题,那么可以在类级别使用实例变量:

    def printer_outside_class(value)
      puts value
    end
    
    class Prints
      @value = 100
      def self.value; @value; end
      def self.value=(neu); @value = neu; end
    
      def initialize(a)
         self.class.value = a
         printer_outside_class(a)
       end
      printer_outside_class(value)
    end
    
    Prints.new(123)
    

    【讨论】:

    • 我喜欢你使用neu 获得 值的方式。 :)
    • @mudasobwa 感谢您的回答。我已经更新了问题以添加更多说明。很抱歉造成混乱。
    • 您的问题更新版本与我的回答有什么共同点?我在类级别使用实例变量。您使用普通实例变量。它们是完全不同的东西,我相信您应该了解类作用域在 ruby​​ 中是如何工作的,在解析时立即执行什么以及延迟到真正的方法调用。
    猜你喜欢
    • 2014-06-08
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 2016-10-12
    • 2011-09-20
    相关资源
    最近更新 更多