【问题标题】:Properties don't change when values are assigned?赋值时属性不会改变?
【发布时间】:2012-03-18 17:54:03
【问题描述】:

我有点 Ruby,菜鸟,有一些基本的东西我没有得到。我有这样的事情:

def my_method
    attr1 = 'new 1 value'
    attr2 = 'new 2 value'
    puts "#{attr1} - #{attr2}"
    puts "Should be same? #{to_s}"
end

def to_s
    "#{attr1} - #{attr2}"
end

当我调用 my_method 时,我得到:

new 1 value - new 2 value 
Should be same? old 1 value - old 2 value

嗯?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord ruby-1.9


    【解决方案1】:

    这是因为在 Ruby 中

    x = y
    

    总是y 产生的值赋值给 变量 x while

    obj.x = y
    

    总是x=消息发送到对象obj(值来自y)。

    在 Ruby 中 attributes/properties 真的只是方法!因此,尝试:

    self.attr1 = 'new 1 value'
    self.attr2 = 'new 2 value'
    

    另一方面,y 可能是也可能不是方法调用(阅读:property fetch)。这取决于范围内是否已经存在变量y,因为变量 shadow 方法。这就是为什么 attr1attr2 可以在 to_s 中工作而无需前缀的原因。

    编码愉快。

    【讨论】:

      【解决方案2】:

      有两种方法可以做到这一点。一种是使用类范围的变量而不是局部变量:

      class MyClass
      
          def my_method
              @attr1 = 'new 1 value'
              @attr2 = 'new 2 value'
              puts "#{@attr1} - #{@attr2}"
              puts "Should be same? #{self.to_s}"
          end
      
          def to_s
              "#{@attr1} - #{@attr2}"
          end
      end
      
      m = MyClass.new
      m.my_method
      

      输出:

      new 1 value - new 2 value
      Should be same? new 1 value - new 2 value
      

      另一种方法是使用属性,您必须在self 上专门将其作为方法调用:

      class MyClass
          attr_accessor :attr1,:attr2
      
          def my_method
              self.attr1 = 'new 1 value'
              self.attr2 = 'new 2 value'
              puts "#{attr1} - #{attr2}"
              puts "Should be same? #{self.to_s}"
          end
      
          def to_s
              "#{attr1} - #{attr2}"
          end
      end
      
      m = MyClass.new
      m.my_method
      

      这具有相同的输出。

      【讨论】:

      • 根据标签,我认为它们很可能是 AR 属性。
      • 在这种情况下,第二种解决方案符合要求,只是他不需要声明访问者。
      【解决方案3】:

      它的作用域attr1attr2 是局部变量。

      因此,当您调用 to_s 时,它会查找您(可能)在类范围内声明的 attr_1attr_2。当您运行 my_method 时,这些不会被覆盖,而是您只是在较小的范围内创建了一个新变量。

      尝试改用@attr_1@attr_2

      查看Local Variable Gotchas

      【讨论】:

      • 基于标签我认为它们是AR属性,否则根本不起作用。
      • 是的,他的问题措辞确实听起来像是一个基本的 Ruby 问题,但是当我第一次开始使用 Rails 和virtual_attributes 时,我确实遇到了这样的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 2015-08-14
      相关资源
      最近更新 更多