【问题标题】:Dynamic properties in ruby classruby 类中的动态属性
【发布时间】:2013-12-06 02:04:16
【问题描述】:

如何在 ruby​​ 中创建动态属性?这个功能存在于python中。

class Example(object):
    value = "This is property!"

class Test(object):
    @property
    def check(self):
        return Example

test = Test()
print(test.check.value)  # This is property!

我怎样才能在 ruby​​ 中做同样的事情?

【问题讨论】:

  • Ruby 没有属性。你能澄清你想让你的代码做什么吗?最好使用 Ruby 主义者可以理解的语言(即 Ruby),但并不是每个 Ruby 主义者都能完全流利地使用 Python。

标签: ruby ruby-1.9.3


【解决方案1】:
class Example
  def value
    "This is property!"
  end
end

class Test
  def check
    Example.new
  end
end

test = Test.new
puts test.check.value  # This is property!

【讨论】:

    【解决方案2】:
    class Test
      def check
       "This is property!"
      end
    end
    
    test = Test.new
    puts(test.check) # This is property!
    

    【讨论】:

    • 我知道这个解决方案。但它是一种方法,而不是一种属性。我不能那样做:test.check.again
    【解决方案3】:

    不确定您希望从示例中得到什么。属性(据我所知)通常用于创建 setter 和 getter。你可以在 Ruby 中使用 attr_accessor:

    class Test
      attr_accessor :check
    end
    

    您可以随时致电attr_accessor 获取属性:

    class Test
      %w{this are possible attribute names}.each do |att|
        attr_accessor att
      end
    end
    

    或者

    Class Test
    end
    
    test = Test.new
    Test.send(:attr_accessor, :whatever)
    test.whatever = "something"
    test.whatever # => "something"
    

    如果你只想要一个吸气剂,你有attr_reader,还有attr_writer 用于作家。对于名为attribute_name 的属性,它们都使用名为@attribute_name 的实例变量。它们都可以使用instance_variable_setinstance_variable_get 构建,它们允许动态设置和获取实例变量。

    【讨论】:

      【解决方案4】:

      您可以使用 ruby​​ 的 method_missing 来实现类似的功能:

      class TestCheck
        def method_missing(methodId)
          if(methodId.id2name == "check")
            puts "check called"
          else
            puts "method not found"
          end
        end
      
      end
      
      t = TestCheck.new
      t.check      #=> "check called"
      t.something_else   #=> "method not found"
      

      参考:Ruby docs

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 1970-01-01
        • 2013-04-14
        • 2021-03-12
        • 2021-02-14
        • 1970-01-01
        • 2023-02-07
        相关资源
        最近更新 更多