ruby类中的动态属性

时间:2013-12-06 02:04:16

标签: ruby ruby-1.9.3

如何在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!

我如何在红宝石中做同样的事情?

4 个答案:

答案 0 :(得分:2)

class Test
  def check
   "This is property!"
  end
end

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

答案 1 :(得分:2)

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 :(得分:1)

不确定你想要的例子。属性(从我所见过的)通常用于创建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"

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

答案 3 :(得分:1)

你可以使用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